Преглед на файлове

Merge remote-tracking branch 'origin/desarrollo' into danieldev

Loncitooo преди 7 месеца
родител
ревизия
b587d4d99c

+ 2 - 2
.env.development.local

@@ -1,7 +1,7 @@
 # Projecto   firebase | jwt
 REACT_APP_PROJECT=firebase
-# REACT_APP_API_URL=http://localhost:8080/
-REACT_APP_API_URL=https://laudlv.api.fourier.audio/
+REACT_APP_API_URL=http://localhost:8080/
+# REACT_APP_API_URL=https://laudlv.api.fourier.audio/
 REACT_APP_WEB_URL=https://laud-lv.web.app/
 # REACT_APP_WEB_URL=https://yager.api.fourier.audio/
 REACT_APP_CLOUD_FUNC=https://us-central1-yagermx.cloudfunctions.net

+ 107 - 0
src/components/Uploader.js

@@ -0,0 +1,107 @@
+import React from "react";
+import { Upload as AntdUpload } from "antd";
+import { DownloadOutlined } from "@ant-design/icons";
+import { respuestas } from "../utilities";
+import { useApp } from "../hooks";
+import PropTypes from "prop-types"
+
+const { REACT_APP_API_URL: baseUrl } = process.env;
+
+const Uploader = ({
+  maxCount,
+  endPoint,
+  setReferencias,
+  setListaArchivos,
+  accept = ".xml, .pdf, .png, .jpg, .doc, .xls, .docx, .xlsx",
+  listaArchivos
+}) => {
+
+  const { token } = useApp();
+
+  const [lista, setLista] = React.useState([]);
+
+  const props = {
+    name: 'archivo',
+    headers: {
+      // Authorization: `Bearer ${token}`,
+    },
+    method: "POST",
+    progress: {
+      strokeColor: {
+        '0%': '#108ee9',
+        '100%': '#87d068',
+      },
+      strokeWidth: 3,
+      format: (percent) => percent && `${parseFloat(percent.toFixed(2))}%`,
+    },
+  };
+
+  const onFinishSubir = ({ fileList }) => {
+    let listaReferencias = [];
+    let _listaArchivos = [];
+    fileList.forEach(file => {
+      const res = {
+        status: file?.xhr?.status,
+        mensaje: file?.response?.mensaje
+      }
+      respuestas(res);
+      _listaArchivos.push(file);
+      if (file?.id) {
+        listaReferencias.push(file);
+      } else {
+        listaReferencias.push(file?.response?.detalle);
+      }
+    });
+    setListaArchivos(_listaArchivos);
+    setReferencias(listaReferencias);
+  };
+
+  const onChangeArchivos = (info) => {
+    setLista(info.fileList)
+    let fileList = info?.fileList;
+    let l = fileList.length;
+    let completo = true;
+    for (let i = 0; i < l; i++) {
+      if (!fileList[i]?.id && !fileList[i]?.xhr) {
+        completo = false;
+      }
+    }
+    if (completo) {
+      onFinishSubir(info)
+    }
+  };
+
+  React.useEffect(() => {
+    if (listaArchivos) {
+      setLista(listaArchivos)
+      return () => setLista([]);
+    }
+  }, [listaArchivos])
+
+  return (
+    <AntdUpload
+      {...props}
+      maxCount={maxCount}
+      action={`${baseUrl}${endPoint}`}
+      multiple={true}
+      listType="picture-card"
+      fileList={lista}
+      onChange={onChangeArchivos}
+      accept={accept}
+      style={{ width: "100%" }}
+    >
+      <DownloadOutlined /> Subir Archivo
+    </AntdUpload>
+  )
+}
+
+Uploader.propTypes = {
+  maxCount: PropTypes.any,
+  endPoint: PropTypes.string.isRequired,
+  setReferencias: PropTypes.any.isRequired,
+  setListaArchivos: PropTypes.any.isRequired,
+  accept: PropTypes.string,
+  listaArchivos: PropTypes.array.isRequired
+}
+
+export default Uploader;

+ 46 - 1
src/utilities/index.js

@@ -1,4 +1,6 @@
+import { notification } from "antd";
 import { NON_DIGIT } from "../constants";
+import React from "react";
 
 const capitalizeFirst = (string) => {
   const split = string.split("-")
@@ -63,6 +65,48 @@ const agregarFaltantes = (data, newData, campo) => {
   return aux;
 };
 
+const respuestas = (res) => {
+
+  let estatus = false
+
+  if (!res) return 'Error en respuesta'
+
+  if ((res?.status >= 400 && res?.status < 499)) {
+    if (res?.errores !== null) {
+      const errores = Object.values(res?.errores)
+      notification.error({
+        message: 'Atención',
+        description: errores.map((e, i) => <React.Fragment key={`${i}-error`}><span>- {e}</span><br /></React.Fragment>),
+        placement: 'bottomRight'
+      })
+      estatus = false
+    } else {
+      notification.error({
+        message: 'Atención',
+        description: res?.mensaje ? res?.mensaje : 'Hubo un problema del lado del servidor.',
+        placement: 'bottomRight'
+      })
+      estatus = false
+    }
+  } else if (res?.status >= 500) {
+    notification.error({
+      message: 'Atención',
+      description: 'Hubo un problema del lado del servidor.',
+      placement: 'bottomRight'
+    })
+    estatus = false
+  } else if (res?.status >= 200 && res?.status < 299) {
+    notification.success({
+      message: '¡Éxito!',
+      description: `${res?.mensaje}`,
+      placement: 'bottomRight'
+    })
+    estatus = true
+  }
+
+  return estatus
+};
+
 export { 
   capitalizeFirst,
   propertyAccesor,
@@ -70,5 +114,6 @@ export {
   validateName,
   validateNumber,
   maskCurrency,
-  agregarFaltantes
+  agregarFaltantes,
+  respuestas
 };

+ 60 - 34
src/views/administracion/eventos/EventoDetalleGrupo.js

@@ -1,4 +1,4 @@
-import React, { useEffect, useState } from "react";
+import React, { useEffect, useMemo, useState } from "react";
 import {
   Col,
   Row,
@@ -31,7 +31,7 @@ import {
   where,
   orderBy,
 } from "firebase/firestore";
-import { useQuery, useAuth } from "../../../hooks";
+import { useQuery, useAuth, useModels } from "../../../hooks";
 import { ViewLoading } from "../../../components";
 import excelCondensado from "../../../services/excelCondensado";
 import { DefaultLayout } from "../../../components/layouts";
@@ -39,6 +39,7 @@ import { firestore } from "../../../services/firebase";
 import locale from "antd/es/date-picker/locale/es_ES";
 import moment from "moment";
 import "moment/locale/es-mx";
+import { emptyRequest } from "../../../constants/requests";
 
 const { RangePicker } = DatePicker;
 const { REACT_APP_WEB_URL } = process.env;
@@ -50,9 +51,9 @@ const EventoDetalleGrupo = () => {
   const { TextArea } = Input;
   const { Meta } = Card;
   const { Option } = Select;
-  const id = query.get("id");
+  // const id = query.get("id");
   const tag = query.get("tag");
-  const editando = !!id;
+  const editando = !!tag;
   const urlweb = "/administracion/eventos";
   const [form] = Form.useForm();
   const [formProcesar] = Form.useForm();
@@ -73,6 +74,22 @@ const EventoDetalleGrupo = () => {
     condensado: false,
   });
 
+  const [request, setRequest] = useState(emptyRequest);
+
+  const requestExtraParams = useMemo(() => ({
+    tag: tag
+  }), [tag]);
+
+  const requestParams = useMemo(() => ({
+    name: 'v1/evento',
+    expand: 'grupos,media',
+    extraParams: requestExtraParams
+  }), [requestExtraParams])
+
+  const [
+    models, modelsLoading, , , ,
+  ] = useModels(request);
+
   const acciones = [
     { id: 0, value: "Ver", label: "Ver", icon: "👁" },
     { id: 1, value: "Me gusta", label: "Me gusta", icon: "👍" },
@@ -190,12 +207,12 @@ const EventoDetalleGrupo = () => {
       // Hay indices que salen en undefined y salió error al guardar en firebase
       try {
         resultado = JSON.parse(JSON.stringify(resultado));
-      } catch (e) {}
+      } catch (e) { }
 
       // Sale un error en firebase de que no puede guardar información en undefined (no se encontró dónde)
       try {
         usuarios = JSON.parse(JSON.stringify(usuarios));
-      } catch (e) {}
+      } catch (e) { }
 
       let body = {
         usuarios,
@@ -205,10 +222,10 @@ const EventoDetalleGrupo = () => {
       await updateDoc(doc(firestore, "eventos", evento?.id), body);
       history.push(
         urlweb +
-          "/resultado-grupo-evento?id=" +
-          evento?.id +
-          "&tag=" +
-          evento?.tag,
+        "/resultado-grupo-evento?id=" +
+        evento?.id +
+        "&tag=" +
+        evento?.tag,
       );
       setVisible(false);
     } catch (error) {
@@ -323,7 +340,7 @@ const EventoDetalleGrupo = () => {
       });
 
       const body = {
-        idEvento: id,
+        // idEvento: id,
         plantilla: plantilla,
         titulo: grupoEvento?.nombre,
         estatus: "Nuevo",
@@ -346,7 +363,7 @@ const EventoDetalleGrupo = () => {
       }
 
       // Buscamos si existe un registro con el ID del evento y la misma plantilla
-      const q = firebaseQuery(
+      /* const q = firebaseQuery(
         collection(firestore, "notificaciones"),
         where("idEvento", "==", id),
       );
@@ -362,7 +379,7 @@ const EventoDetalleGrupo = () => {
       if (c > 0) {
         message.info("Ya hay un recordatorio de este evento.");
         return;
-      }
+      } */
 
       await addDoc(collection(firestore, "notificaciones"), body);
       message.success("Recordatorio enviado.");
@@ -434,7 +451,7 @@ const EventoDetalleGrupo = () => {
       });
 
       const body = {
-        idEvento: id,
+        // idEvento: id,
         plantilla: plantilla,
         titulo: grupoEvento?.nombre,
         estatus: "Nuevo",
@@ -457,7 +474,7 @@ const EventoDetalleGrupo = () => {
       }
 
       // Buscamos si existe un registro con el ID del evento y la misma plantilla
-      const q = firebaseQuery(
+      /* const q = firebaseQuery(
         collection(firestore, "notificaciones"),
         where("idEvento", "==", id),
       );
@@ -474,7 +491,7 @@ const EventoDetalleGrupo = () => {
       if (c > 0) {
         message.info("Ya hay un recordatorio de este evento.");
         return;
-      }
+      } */
 
       await addDoc(collection(firestore, "notificaciones"), body);
       message.success("Recordatorio guardado.");
@@ -557,7 +574,7 @@ const EventoDetalleGrupo = () => {
       }
 
       const body = {
-        idEvento: id,
+        // idEvento: id,
         plantilla: plantilla,
         titulo: grupoEvento?.nombre,
         enviado: null,
@@ -580,7 +597,7 @@ const EventoDetalleGrupo = () => {
       }
 
       // Buscamos si existe un registro con el ID del evento y la misma plantilla
-      const q = firebaseQuery(
+      /* const q = firebaseQuery(
         collection(firestore, "notificaciones"),
         where("idEvento", "==", id),
       );
@@ -599,7 +616,7 @@ const EventoDetalleGrupo = () => {
       }
 
       await addDoc(collection(firestore, "notificaciones"), body);
-      message.success("Recordatorio enviado.");
+      message.success("Recordatorio enviado."); */
     } catch (error) {
       message.error("Error al enviar la notificacion");
       console.log("error al enviar felicitación: ", error);
@@ -809,7 +826,12 @@ const EventoDetalleGrupo = () => {
     }
   };
 
-  // Obtener grupo
+  useEffect(() => {
+    setRequest(requestParams);
+    return () => setRequest(emptyRequest);
+  }, [requestParams])
+
+  /* // Obtener grupo
   useEffect(() => {
     let mounted = true;
     if (mounted && editando) {
@@ -826,13 +848,17 @@ const EventoDetalleGrupo = () => {
       }
     }
     return () => (mounted = false);
-  }, [editando, id]);
+  }, [editando, id]); */
 
   // Obtener eventos del grupo
   useEffect(() => {
     let mounted = true;
     if (mounted && editando) {
-      try {
+      if (models) {
+        setEventos(models);
+        setCargandoEvento(false);
+      }
+      /* try {
         setTimeout(async () => {
           const q = firebaseQuery(
             collection(firestore, "eventos"),
@@ -853,23 +879,23 @@ const EventoDetalleGrupo = () => {
         console.log("error al obtener evento: ", error);
       } finally {
         setCargandoEvento(false);
-      }
+      } */
     }
     return () => (mounted = false);
-  }, [editando, tag]);
+  }, [editando, models]);
 
   useEffect(() => {
     let mounted = true;
-    if (mounted && grupoEvento && editando) {
-      setPreviaImg(grupoEvento?.pathFirebase);
+    if (mounted && (eventos && eventos?.length > 0) && editando) {
+      setPreviaImg(eventos[0]?.media?.ruta);
       form.setFieldsValue({
-        ...grupoEvento,
-        fechaFinal: moment(grupoEvento?.fechaFinal),
-        fechaInicio: moment(grupoEvento?.fechaInicio),
+        ...eventos[0],
+        fechaFinal: moment(eventos[0]?.fechaFinal),
+        fechaInicio: moment(eventos[0]?.fechaInicio),
       });
     }
     return () => (mounted = false);
-  }, [editando, grupoEvento, form]);
+  }, [editando, eventos, form, grupoEvento?.pathFirebase]);
 
   if (cargandoEvento) return <ViewLoading />;
 
@@ -1141,10 +1167,10 @@ const EventoDetalleGrupo = () => {
                       onClick={() =>
                         history.push(
                           urlweb +
-                            "/resultado-grupo-evento?id=" +
-                            e?.id +
-                            "&tag=" +
-                            e?.tag,
+                          "/resultado-grupo-evento?id=" +
+                          e?.id +
+                          "&tag=" +
+                          e?.tag,
                         )
                       }
                       icon={<BarChartOutlined />}

+ 130 - 45
src/views/administracion/eventos/EventosDetalle.js

@@ -1,4 +1,4 @@
-import React, { useEffect, useState } from "react";
+import React, { useEffect, useMemo, useState } from "react";
 import {
   Col,
   Row,
@@ -46,10 +46,14 @@ import {
   getDownloadURL,
 } from "firebase/storage";
 
-import { useQuery } from "../../../hooks";
+import { useModel, useModels, useQuery } from "../../../hooks";
 import { ViewLoading } from "../../../components";
 import { DefaultLayout } from "../../../components/layouts";
 import { firestore, storage, database } from "../../../services/firebase";
+import Uploader from "../../../components/Uploader";
+import { emptyRequest } from "../../../constants/requests";
+import HttpService from "../../../services/httpService";
+import { respuestas } from "../../../utilities";
 
 const EventosDetalle = () => {
   const urlweb = "/administracion/eventos";
@@ -67,7 +71,7 @@ const EventosDetalle = () => {
   const [sinFechaFin, setSinFechaFin] = useState(false);
   const [visible, setVisible] = useState(false);
   const [cargandoGrupos, setCargandoGrupos] = useState(true);
-  const [grupos, setGrupos] = useState([]);
+  // const [grupos, setGrupos] = useState([]);
   const [filteredResults, setFilteredResults] = useState([]);
   const [searchInput, setSearchInput] = useState("");
   const [selectedGrupos, setSelectedGrupos] = useState([]);
@@ -76,6 +80,34 @@ const EventosDetalle = () => {
   const [previaImg, setPreviaImg] = useState(null);
   const [redes, setRedes] = useState([]);
 
+  const [listaArchivos, setListaArchivos] = useState();
+  const [referencias, setReferencias] = useState();
+  const [requestGrupos, setRequestGrupos] = useState(emptyRequest);
+  const [request, setRequest] = useState(emptyRequest);
+
+  const requestParams = useMemo(() => ({
+    name: 'v1/evento',
+    id: id,
+    expand: 'media,grupos,eventoAcciones'
+  }), [id]);
+
+  const gruposParams = useMemo(() => ({
+    name: 'v1/grupo'
+  }), []);
+
+  const {
+    model,
+    modelLoading
+  } = useModel(request);
+
+  const [
+    grupos,
+    gruposLoading,
+    ,
+    ,
+    ,
+  ] = useModels(requestGrupos)
+
   const defaultText = (prop) =>
     prop || <span style={{ color: "#c7c3c3" }}>---</span>;
 
@@ -200,7 +232,7 @@ const EventosDetalle = () => {
     const storage = getStorage();
     const desertRef = refStorage(storage, fileRoute);
     deleteObject(desertRef)
-      .then((e) => {})
+      .then((e) => { })
       .catch((error) => {
         console.log(error);
       });
@@ -223,6 +255,7 @@ const EventosDetalle = () => {
 
   const onFinish = async (values) => {
     try {
+      // debugger
       const {
         accion,
         ciudad,
@@ -238,7 +271,7 @@ const EventosDetalle = () => {
 
       let file = selectedFile ? selectedFile.originFileObj : null;
 
-      if (!editando && !file) {
+      if (!editando && referencias?.length === 0) {
         Modal.warning({
           title: "Atención",
           content: "Debes subir una imagen del evento.",
@@ -250,7 +283,7 @@ const EventosDetalle = () => {
       let pathFirebase = evento?.pathFirebase;
 
       if (file) {
-        if (editando) {
+        /* if (editando) {
           await eliminarImagen(evento?.fotoEvento);
         }
 
@@ -263,10 +296,10 @@ const EventosDetalle = () => {
           pathFirebase = await getDownloadURL(res?.ref);
         } catch (error) {
           console.log("Error en el uploadbytes: ", error);
-        }
+        } */
       }
 
-      const docsUsuarios = await obtenerUsuariosGrupo();
+      /* const docsUsuarios = await obtenerUsuariosGrupo();
 
       let resultado = { ...evento?.resultado };
       let usuarios = [];
@@ -296,14 +329,14 @@ const EventosDetalle = () => {
           instagramVerificado: Boolean(docsUsuarios[u]?.instagramVerificado),
           twitterVerificado: Boolean(docsUsuarios[u]?.twitterVerificado),
         });
-      }
+      } */
 
       let body = {
         accion: accion || [],
         ciudad: ciudad || "",
         descripcion: descripcion || "",
-        fechaFinal: fechaFinal?.toString() || "",
-        fechaInicio: fechaInicio?.toString(),
+        fechaFinal: fechaFinal ? moment(fechaFinal)?.format() : null,
+        fechaInicio: fechaInicio ? moment(fechaInicio)?.format() : null,
         sinFechaFin: sinFechaFin,
         nombre: nombre || "",
         redSocial: redSocial || "",
@@ -313,13 +346,25 @@ const EventosDetalle = () => {
         pathFirebase: pathFirebase,
         timestamp: editando ? evento?.timestamp : new Date(),
         estatus: editando ? evento?.estatus : true,
-        usuarios: usuarios,
+        media: referencias,
+        // usuarios: usuarios,
         redes: redes,
-        resultado: resultado,
+        // resultado: resultado,
         sincronizado: null,
       };
 
-      const tag = makeid(8);
+      let tag = '';
+      if (!editando) {
+        tag = makeid(8);
+      } else if (editando && id) {
+        body.id = id;
+        if (model?.tag) {
+          tag = model?.tag;
+        }
+      }
+
+      body.tag = tag;
+
       let grupoEventoRef = null;
       //Crear grupo de eventos
       if (redes.length > 0) {
@@ -336,24 +381,36 @@ const EventosDetalle = () => {
           pathFirebase: pathFirebase,
           timestamp: editando ? evento?.timestamp : new Date(),
           estatus: editando ? evento?.estatus : true,
-          tag: tag,
+          // tag: tag,
           redes: redes,
-          usuarios: usuarios,
-          resultado: resultado,
+          // usuarios: usuarios,
+          // resultado: resultado,
         };
 
-        grupoEventoRef = await addDoc(
+        /* grupoEventoRef = await addDoc(
           collection(firestore, "gruposEvento"),
           grupoEvento,
-        );
+        ); */
       }
 
       if (editando) {
-        await updateDoc(doc(firestore, "eventos", id), body);
-        return;
+        const res = await HttpService.post('v1/evento', body);
+        respuestas(res);
+        if (res?.status === 200) {
+          // history.push(`${urlweb}/detalleGrupo?id=${grupoEventoRef.id}&tag=${tag}`);
+          history.push(`${urlweb}`);
+        }
+      } else {
+        const res = await HttpService.post('v1/evento/guardar-grupo', body);
+        respuestas(res);
+
+        if (res?.status === 200) {
+          // history.push(`${urlweb}/detalleGrupo?id=${grupoEventoRef.id}&tag=${tag}`);
+          history.push(`${urlweb}`);
+        }
       }
 
-      for (let i = 0; i < redes?.length; i++) {
+      /* for (let i = 0; i < redes?.length; i++) {
         body = {
           ...body,
           redSocial: redes[i]?.redSocial,
@@ -363,15 +420,14 @@ const EventosDetalle = () => {
         if (!editando) {
           body["tag"] = tag;
         }
-        await addDoc(collection(firestore, "eventos"), body);
-      }
+        // await addDoc(collection(firestore, "eventos"), body);
+      } */
 
-      Modal.success({
-        title: "Éxito",
-        content: "Evento guardado correctamente",
-      });
+      // Modal.success({
+      //   title: "Éxito",
+      //   content: "Evento guardado correctamente",
+      // });
 
-      history.push(`${urlweb}/detalleGrupo?id=${grupoEventoRef.id}&tag=${tag}`);
     } catch (error) {
       Modal.warning({
         title: "Atención",
@@ -489,8 +545,20 @@ const EventosDetalle = () => {
     }
   };
 
+  useEffect(() => {
+    setRequest(requestParams);
+    return () => setRequest(emptyRequest);
+  }, [requestParams])
+
   // Grupos
   useEffect(() => {
+    setRequestGrupos(gruposParams);
+    return () => {
+      setRequestGrupos(emptyRequest);
+    }
+  }, [gruposParams]);
+
+  /* useEffect(() => {
     try {
       onSnapshot(collection(firestore, "grupos"), (querySnapshot) => {
         const docs = [];
@@ -506,7 +574,7 @@ const EventosDetalle = () => {
     } finally {
       setCargandoGrupos(false);
     }
-  }, []);
+  }, []); */
 
   // Limpiar imagen
   useEffect(() => {
@@ -516,7 +584,7 @@ const EventosDetalle = () => {
   }, [selectedFile]);
 
   // Obtener detalles del evento.
-  useEffect(() => {
+  /* useEffect(() => {
     let mounted = true;
     if (mounted && editando) {
       try {
@@ -532,25 +600,35 @@ const EventosDetalle = () => {
       }
     }
     return () => (mounted = false);
-  }, [editando, id]);
+  }, [editando, id]); */
 
   useEffect(() => {
     let mounted = true;
-    if (mounted && evento && editando) {
-      setPreviaImg(evento?.pathFirebase);
-      setSinFechaFin(evento?.sinFechaFin);
-      setSelectedGrupos(evento?.grupos);
+    if (mounted && model && editando) {
+      setReferencias([model?.media])
+      // setPreviaImg(model?.media?.ruta);
+      setSinFechaFin(model?.sinFechaFin);
+      setSelectedGrupos(model?.grupos?.map((g) => g.id));
       form.setFieldsValue({
-        ...evento,
-        fechaFinal: moment(evento?.fechaFinal),
-        fechaInicio: moment(evento?.fechaInicio),
+        ...model,
+        fechaFinal: model?.fechaFinal ? moment(model?.fechaFinal) : null,
+        fechaInicio: model?.fechaInicio ? moment(model?.fechaInicio) : null,
+        accion: model?.eventoAcciones ? model?.eventoAcciones.map((i) => i.accion) : null
       });
     }
     return () => (mounted = false);
-  }, [editando, evento, form]);
+  }, [editando, form, model]);
+
+  useEffect(() => {
+    if (referencias && referencias?.length > 0) {
+      setPreviaImg(referencias[0]?.ruta)
+    }
+  }, [referencias])
 
   if (cargandoEvento && editando) return <ViewLoading />;
 
+  console.log('model: ', model)
+
   return (
     <DefaultLayout multipleButtonData={multipleButtonData}>
       <Modal
@@ -581,7 +659,7 @@ const EventosDetalle = () => {
             selectedRowKeys: selectedGrupos,
             ...rowSelection,
           }}
-          loading={cargandoGrupos}
+          loading={gruposLoading}
           columns={columns}
           size="small"
           scroll={{ x: 700 }}
@@ -618,13 +696,20 @@ const EventosDetalle = () => {
                   name="upload"
                   label="Imagen del evento"
                   valuePropName="fileList"
-                  rules={[
+                  /* rules={[
                     { required: editando ? false : true, message: "Requerido" },
-                  ]}
+                  ]} */
                   getValueFromEvent={normFile}
                   extra={editando && evento ? evento?.fotoEvento : null}
                 >
-                  <Upload
+                  <Uploader
+                    maxCount="1"
+                    endPoint={'v1/subir-archivo/guardar'}
+                    setListaArchivos={setListaArchivos}
+                    listaArchivos={listaArchivos}
+                    setReferencias={setReferencias}
+                  />
+                  {/* <Upload
                     accept="image/gif, image/jpeg, image/png"
                     fileList={selectedFileList}
                     customRequest={dummyRequest}
@@ -634,7 +719,7 @@ const EventosDetalle = () => {
                     maxCount={1}
                   >
                     <Button icon={<UploadOutlined />}>Elegir imagen</Button>
-                  </Upload>
+                  </Upload> */}
                 </Form.Item>
               </Col>
 

+ 116 - 83
src/views/administracion/eventos/EventosListado.js

@@ -1,5 +1,5 @@
 import React, { useEffect, useState, useCallback } from 'react';
-import { Table, Modal, Button, message, Input, Row, Col, Tabs,  Divider } from 'antd';
+import { Table, Modal, Button, message, Input, Row, Col, Tabs, Divider } from 'antd';
 import { EditOutlined, DeleteOutlined, BarChartOutlined, PlusCircleOutlined, ExclamationCircleOutlined, DeliveredProcedureOutlined } from "@ant-design/icons";
 import { useHistory } from 'react-router-dom';
 import moment from 'moment';
@@ -8,6 +8,9 @@ import { ActionsButton } from '../../../components';
 import { SimpleTableLayout } from '../../../components/layouts';
 import { collection, limit, orderBy, updateDoc, doc, getDocs, query, where, addDoc } from "firebase/firestore";
 import { useAuth } from '../../../hooks';
+import Tabla from '../../../components/Tabla';
+import HttpService from '../../../services/httpService';
+import { respuestas } from '../../../utilities';
 
 const { REACT_APP_WEB_URL } = process.env;
 
@@ -19,18 +22,18 @@ const EventosListado = () => {
   const url = "/administracion/eventos";
   const history = useHistory();
   const { confirm } = Modal;
-  
-  const [ eventos, setEventos ] = useState([]);
-  const [ grupoEventos, setGrupoEventos ] = useState([]);
-  const [ filteredResults, setFilteredResults ] = useState([]);
-  const [ searchInput, setSearchInput ] = useState('');
-  const [ visible, setVisible ] = useState(false);
-  const [ textAreaData, setTextAreaData ] = useState('');
-  const [ evento, setEvento ] = useState(null);
-  const [ procesando, setProcesando ] = useState(false);
-  const [ eventosPorPagina, setEventosPorPagina] = useState(10);
-  const [ currentPage, setCurrentPage] = useState(1);
-  
+
+  const [eventos, setEventos] = useState([]);
+  const [grupoEventos, setGrupoEventos] = useState([]);
+  const [filteredResults, setFilteredResults] = useState([]);
+  const [searchInput, setSearchInput] = useState('');
+  const [visible, setVisible] = useState(false);
+  const [textAreaData, setTextAreaData] = useState('');
+  const [evento, setEvento] = useState(null);
+  const [procesando, setProcesando] = useState(false);
+  const [eventosPorPagina, setEventosPorPagina] = useState(10);
+  const [currentPage, setCurrentPage] = useState(1);
+
   const defaultText = prop => prop || <span style={{ color: '#c7c3c3' }}>---</span>;
 
   const pageSizeOptions = ['10', '20', '30', '40', '50', '60', '70', '80'];
@@ -42,20 +45,20 @@ const EventosListado = () => {
       key: "id",
       align: "center",
       width: 100,
-      render: (_, item ) => (
+      render: (_, item) => (
         <ActionsButton
           key={item}
           options={[
             {
               name: "Editar",
               icon: <EditOutlined />,
-              onClick: () => history.push(url+'/detalle?id='+item.id)
+              onClick: () => history.push(url + '/detalle?id=' + item.id)
             },
             {
               name: "Ver resultados",
               disabled: !item?.resultado,
               icon: <BarChartOutlined />,
-              onClick: () => history.push(url+'/resultado-acciones?id='+item?.id),
+              onClick: () => history.push(url + '/resultado-acciones?id=' + item?.id),
             },
             {
               name: "Procesador",
@@ -69,7 +72,7 @@ const EventosListado = () => {
             {
               name: "Eliminar",
               icon: <DeleteOutlined />,
-              onClick: () => eliminarRegistro(item, 'eventos'),
+              onClick: () => eliminarRegistro(item, 'evento'),
               styleProps: { color: '#e91e63' },
             },
           ]}
@@ -87,30 +90,30 @@ const EventosListado = () => {
       dataIndex: "redSocial",
       key: "redSocial",
       align: 'center',
-      render: ( _, item ) => (
-        <img src={  '/assets/'+item?.redSocial+'.png'  } width='40' alt="Red social" />
+      render: (_, item) => (
+        <img src={'/assets/' + item?.redSocial + '.png'} width='40' alt="Red social" />
       ),
     },
     {
       title: "Creado",
-      dataIndex: "timestamp",
-      key: "timestamp",
+      dataIndex: "creado",
+      key: "creado",
       render: (_, item) => (
-        moment(item?.timestamp?.toDate()).format('DD-MM-YYYY')
+        moment(item?.creado).format('DD-MM-YYYY')
       ),
     },
     {
-      title: 'URL Laud', 
+      title: 'URL Laud',
       dataIndex: "id",
       key: "id",
       align: "center",
       width: 100,
-      render: (_, item ) => (
+      render: (_, item) => (
         <Button
           type='link'
-          onClick={ () => obtenerEnlaceYager(item) }
+          onClick={() => obtenerEnlaceYager(item)}
         >
-          <img src="/assets/LAUD-Avatar.png" width='40' alt="icono" style={{ position: 'relative', marginTop: -11  }} />
+          <img src="/assets/LAUD-Avatar.png" width='40' alt="icono" style={{ position: 'relative', marginTop: -11 }} />
         </Button>
       )
     }
@@ -123,7 +126,7 @@ const EventosListado = () => {
       key: "id",
       align: "center",
       width: 100,
-      render: (_, item ) => (
+      render: (_, item) => (
         <ActionsButton
           key={item}
           options={[
@@ -153,16 +156,16 @@ const EventosListado = () => {
       dataIndex: "redes",
       key: "redes",
       align: 'center',
-      render: ( _, item ) => {
-        return item?.redes.map( (i, index) => Array.from(item.redes.keys()).pop() !== index ? i.redSocial + ', ' : i.redSocial + '' )        
+      render: (_, item) => {
+        return item?.redes/* .map((i, index) => Array.from(item.redes.keys()).pop() !== index ? i.redSocial + ', ' : i.redSocial + '') */
       },
     },
     {
       title: "Creado",
-      dataIndex: "timestamp",
-      key: "timestamp",
+      dataIndex: "creado",
+      key: "creado",
       render: (_, item) => (
-        moment(item?.timestamp?.toDate()).format('DD-MM-YYYY')
+        moment(item?.creado).format('DD-MM-YYYY')
       ),
     },
     {
@@ -175,12 +178,12 @@ const EventosListado = () => {
   const multipleButtonData = [
     {
       text: "Agregar",
-      to: () => history.push(url+'/nuevo'),
+      to: () => history.push(url + '/nuevo'),
       icon: <PlusCircleOutlined />,
       props: { disabled: false, type: 'primary', }
-    }, 
+    },
   ];
- 
+
   const ModalProcesar = () => {
     return (
       <Modal
@@ -219,7 +222,15 @@ const EventosListado = () => {
 
   const TablaGrupos = () => {
     return (
-      <Table
+      <>
+        <Tabla
+          nameURL={'v1/evento/por-grupo'}
+          columns={columnasGrupos}
+          extraParams={{ q: searchInput }}
+          order={'creado-desc'}
+          scroll={{ x: "30vw" }}
+        />
+        {/* <Table
         dataSource={searchInput.length > 1 ? filteredResults : grupoEventos}
         rowKey={"id"}
         columns={columnasGrupos}
@@ -235,41 +246,51 @@ const EventosListado = () => {
             setEventosPorPagina(pageSize)
           }
         }}
-      />
+      /> */}
+      </>
     )
   };
 
   const TablaEventos = () => {
     return (
-      <Table
+      <>
+        <Tabla
+          nameURL={'v1/evento'}
+          columns={columnasEventos}
+          extraParams={{ q: searchInput }}
+          order={'creado-desc'}
+          scroll={{ x: "30vw" }}
+        />
+        {/* <Table
         dataSource={searchInput.length > 1 ? filteredResults : eventos}
         rowKey={"id"}
         columns={columnasEventos}
         size='small'
         scroll={{ x: 700 }}
-        pagination={{ 
+        pagination={{
           current: currentPage,
-          defaultPageSize: eventosPorPagina, 
-          showSizeChanger: true, 
+          defaultPageSize: eventosPorPagina,
+          showSizeChanger: true,
           pageSizeOptions: pageSizeOptions,
           onChange: (page, pageSize) => {
             setCurrentPage(page)
             setEventosPorPagina(pageSize)
           }
         }}
-      />
+      /> */}
+      </>
     )
   };
-   
-  function b64_to_utf8( str ) {
-    return decodeURIComponent(escape(window.atob( str )));
+
+  function b64_to_utf8(str) {
+    return decodeURIComponent(escape(window.atob(str)));
   };
 
   const guardarRegistro = async () => {
     try {
 
       const json = JSON.parse(textAreaData);
-      const accion =  b64_to_utf8(json.accion).split(".");  
+      const accion = b64_to_utf8(json.accion).split(".");
       const lista = json[json.tipo][accion[0]];
 
       const body = {
@@ -296,30 +317,30 @@ const EventosListado = () => {
       const usuarios = await obtenerUsuariosGrupo();
 
       const json = JSON.parse(textAreaData);
-      const accion =  b64_to_utf8(json.accion).split(".");  
+      const accion = b64_to_utf8(json.accion).split(".");
       const lista = json[json.tipo][accion[0]];
 
-      if( json?.tipo !==  evento?.redSocial?.toLowerCase() ) {
+      if (json?.tipo !== evento?.redSocial?.toLowerCase()) {
         message.warning({
           content: 'La red social es incorrecta',
         });
         return
       }
 
-      let resultado = {...evento.resultado};
-      for( let u = 0; u < usuarios?.length; u++ ) {
+      let resultado = { ...evento.resultado };
+      for (let u = 0; u < usuarios?.length; u++) {
         let usuarioTipo = usuarios[u][json.tipo]?.toLowerCase();
 
-        if( resultado[usuarios[u]?.uid] === undefined ) {
+        if (resultado[usuarios[u]?.uid] === undefined) {
           resultado[usuarios[u]?.uid] = [];
         }
 
-        if( usuarioTipo?.toLowerCase() ) {
-          for( let i = 0; i < lista.length; i++ ) {       
+        if (usuarioTipo?.toLowerCase()) {
+          for (let i = 0; i < lista.length; i++) {
             const nick = lista[i]?.replace("@", "").toLowerCase();
 
-            if(nick?.includes(usuarios[u][json.tipo])) {
-              if( !resultado[usuarios[u]?.uid].includes(accion[0]) ) {
+            if (nick?.includes(usuarios[u][json.tipo])) {
+              if (!resultado[usuarios[u]?.uid].includes(accion[0])) {
                 resultado[usuarios[u]?.uid].push(accion[0])
               }
             }
@@ -333,10 +354,10 @@ const EventosListado = () => {
       }
 
       await updateDoc(doc(firestore, "eventos", evento?.id), body);
-      if(evento?.tag){ 
-        history.push( url+'/resultado-grupo-evento?id='+evento?.id+"&tag="+evento?.tag);
-      } else  {
-        history.push( url+'/resultado?id='+evento?.id);
+      if (evento?.tag) {
+        history.push(url + '/resultado-grupo-evento?id=' + evento?.id + "&tag=" + evento?.tag);
+      } else {
+        history.push(url + '/resultado?id=' + evento?.id);
       }
       setVisible(false);
 
@@ -345,7 +366,7 @@ const EventosListado = () => {
       message.warning({
         content: 'Atención: hubo un problema al procesar la información',
       });
-    }  finally {
+    } finally {
       setProcesando(false);
     };
 
@@ -357,7 +378,7 @@ const EventosListado = () => {
     const _grupos = evento?.grupos;
 
     // Verificar que el evento no tenga grupos
-    if( _grupos?.length === 0 ) {
+    if (_grupos?.length === 0) {
       message.warning({
         content: 'Atención: el evento no tiene grupos.',
       });
@@ -365,27 +386,27 @@ const EventosListado = () => {
     };
 
     try {
-      
-      const q = query(collection(firestore, "usuarios"), where('grupos', 'array-contains-any',  _grupos ));
+
+      const q = query(collection(firestore, "usuarios"), where('grupos', 'array-contains-any', _grupos));
       const querySnapshot = await getDocs(q);
       const docs = []
 
       querySnapshot.forEach((doc) => {
         const data = doc.data();
-        if(data?.estatus) {
-          docs.push({ 
-            grupos: data?.grupos, 
-            facebook: data?.facebook?.toLowerCase().trim(), 
-            twitter: data?.twitter?.toLowerCase().trim(), 
+        if (data?.estatus) {
+          docs.push({
+            grupos: data?.grupos,
+            facebook: data?.facebook?.toLowerCase().trim(),
+            twitter: data?.twitter?.toLowerCase().trim(),
             instagram: data?.instagram?.toLowerCase().trim(),
-            telefono: data?.telefono, 
-            nombre: data?.nombre, 
+            telefono: data?.telefono,
+            nombre: data?.nombre,
             uid: data?.uid,
-            id:doc.id 
+            id: doc.id
           });
         }
       });
-    
+
       return docs;
 
     } catch (error) {
@@ -395,7 +416,7 @@ const EventosListado = () => {
   };
 
   const obtenerEnlaceYager = (item) => {
-    const url = REACT_APP_WEB_URL+'evento-laud?id='+item?.id;
+    const url = REACT_APP_WEB_URL + 'evento-laud?id=' + item?.id;
     navigator.clipboard.writeText(url);
     message.info({
       content: 'Se ha copiado el enlace al portapapeles.',
@@ -411,32 +432,44 @@ const EventosListado = () => {
       content: '¿Seguro que desea eliminar este registro?',
       onOk: async () => {
         try {
-          await updateDoc(doc(firestore, docs, item?.id), {estatus: false}); 
+          if (docs === "gruposEvento") {
+            // await updateDoc(doc(firestore, docs, item?.id), { estatus: false });
+            const res = await HttpService.post('v1/evento/eliminar-grupo', { tag: item?.tag });
+            respuestas(res);
+            if (res?.status === 200) {
+              window.location.reload(false);
+            }
+          } else if (docs === 'evento') {
+            const res = await HttpService.post('v1/evento/eliminar', { id: item?.id });
+            respuestas(res);
+            if (res?.status === 200) {
+              window.location.reload(false);
+            }
+          }
         } catch (error) {
           console.log('error al eliminar: ', error);
-        } finally {
-          window.location.reload(false);
-        }
+        } /* finally {
+        } */
       },
-      onCancel() {},
+      onCancel() { },
     });
   };
 
   const onSearch = (searchValue) => {
     setSearchInput(searchValue);
-    if( searchValue !== '' ){
+    if (searchValue !== '') {
       const filteredData = eventos.filter((item) => {
         return Object.values(item).join('').toLowerCase().includes(searchValue.toLowerCase());
       })
       setFilteredResults(filteredData);
-    }else{
+    } else {
       setFilteredResults(eventos)
     }
   };
 
-  const obtenerRegistrosFirebase =  useCallback(async (coleccion) => {
+  const obtenerRegistrosFirebase = useCallback(async (coleccion) => {
 
-    if(!coleccion) {
+    if (!coleccion) {
       console.log('Se necesita coleccion');
       return
     }
@@ -447,7 +480,7 @@ const EventosListado = () => {
       const querySnapshot = await getDocs(q);
       const docs = [];
       querySnapshot.forEach((doc) => {
-        if( doc.data()?.estatus ) { 
+        if (doc.data()?.estatus) {
           docs.push({ ...doc.data(), id: doc.id });
         }
       });