| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209 |
- import React, { useEffect, useState } from "react";
- import {
- Col,
- Row,
- Form,
- Input,
- Modal,
- Card,
- Avatar,
- Select,
- Button,
- DatePicker,
- message,
- Spin,
- } from "antd";
- import {
- EditOutlined,
- DeliveredProcedureOutlined,
- BarChartOutlined,
- BellFilled,
- } from "@ant-design/icons";
- import { useHistory } from "react-router-dom";
- import {
- addDoc,
- collection,
- doc,
- getDoc,
- updateDoc,
- query as firebaseQuery,
- getDocs,
- where,
- orderBy,
- } from "firebase/firestore";
- import { useQuery, useAuth } from "../../../hooks";
- import { ViewLoading } from "../../../components";
- import excelCondensado from "../../../services/excelCondensado";
- import { DefaultLayout } from "../../../components/layouts";
- import { firestore } from "../../../services/firebase";
- import locale from "antd/es/date-picker/locale/es_ES";
- import moment from "moment";
- import "moment/locale/es-mx";
- const { RangePicker } = DatePicker;
- const { REACT_APP_WEB_URL } = process.env;
- const EventoDetalleGrupo = () => {
- const query = useQuery();
- const history = useHistory();
- const { session } = useAuth();
- const { TextArea } = Input;
- const { Meta } = Card;
- const { Option } = Select;
- const id = query.get("id");
- const tag = query.get("tag");
- const editando = !!id;
- const urlweb = "/administracion/eventos";
- const [form] = Form.useForm();
- const [formProcesar] = Form.useForm();
- const [grupoEvento, setGrupoEvento] = useState([]);
- const [cargandoEvento, setCargandoEvento] = useState(true);
- const [eventos, setEventos] = useState([]);
- const [visible, setVisible] = useState(false);
- const [visibleReporte, setVisibleReporte] = useState(false);
- const [procesando, setProcesando] = useState(false);
- const [evento, setEvento] = useState(null);
- const [textAreaData, setTextAreaData] = useState("");
- const [previaImg, setPreviaImg] = useState(null);
- const [guardando, setGuardando] = useState({
- nuevo: false,
- faltante: false,
- felicitacion: false,
- condensado: false,
- });
- const acciones = [
- { id: 0, value: "Ver", label: "Ver", icon: "👁" },
- { id: 1, value: "Me gusta", label: "Me gusta", icon: "👍" },
- { id: 2, value: "Compartir", label: "Compartir", icon: "🔄" },
- ];
- const buttons = [
- {
- text: "Notificar nuevo evento",
- to: () => notificarNuevoEvento(),
- icon: <BellFilled />,
- props: {
- disabled: false,
- style: { background: "#2196f3", color: "#fff" },
- type: "default",
- size: "large",
- loading: guardando.nuevo,
- },
- },
- {
- text: "Enviar faltantes",
- to: () => enviarRecordatorios(),
- icon: <BellFilled />,
- props: {
- disabled: false,
- type: "danger",
- size: "large",
- loading: guardando.faltante,
- },
- },
- {
- text: "Enviar felicitación",
- to: () => enviarFelicitacion(),
- icon: <BellFilled />,
- props: {
- disabled: false,
- type: "primary",
- size: "large",
- loading: guardando.felicitacion,
- },
- },
- {
- text: "Reporte condensado",
- to: () => setVisibleReporte(true),
- icon: <BarChartOutlined />,
- props: { disabled: false, type: "dashed", size: "large" },
- },
- ];
- 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 lista = json[json.tipo][accion[0]];
- const body = {
- json: textAreaData,
- accion: accion,
- lista: lista,
- timestamp: new Date(),
- evento: evento,
- usuario: {
- uid: session?.uid,
- email: session?.email,
- displayName: session?.displayName,
- },
- };
- await addDoc(collection(firestore, "procesos"), body);
- } catch (error) {
- console.log("error al guardar registro: ", error);
- }
- };
- const procesarUsuarios = async () => {
- try {
- setProcesando(true);
- let usuarios = await obtenerUsuariosGrupo();
- const json = JSON.parse(textAreaData);
- const accion = b64_to_utf8(json.accion).split(".");
- const lista = json[json.tipo][accion[0]];
- 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 usuarioTipo = usuarios[u][json.tipo]?.toLowerCase();
- if (resultado[usuarios[u]?.uid] === undefined) {
- resultado[usuarios[u]?.uid] = [];
- }
- 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])) {
- resultado[usuarios[u]?.uid].push(accion[0]);
- }
- }
- }
- }
- }
- // Hay indices que salen en undefined y salió error al guardar en firebase
- try {
- resultado = JSON.parse(JSON.stringify(resultado));
- } 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) { }
- let body = {
- usuarios,
- resultado,
- };
- await updateDoc(doc(firestore, "eventos", evento?.id), body);
- history.push(
- urlweb +
- "/resultado-grupo-evento?id=" +
- evento?.id +
- "&tag=" +
- evento?.tag,
- );
- setVisible(false);
- } catch (error) {
- console.log("Error al procesar: ", error);
- message.warning({
- content: "Atención: hubo un problema al procesar la información",
- });
- } finally {
- setProcesando(false);
- }
- };
- const obtenerUsuariosGrupo = async () => {
- const _grupos = grupoEvento?.grupos;
- // Verificar que el evento no tenga grupos
- if (_grupos?.length === 0) {
- message.warning({
- content: "Atención: el evento no tiene grupos.",
- });
- return;
- }
- try {
- const q = firebaseQuery(
- collection(firestore, "usuarios"),
- where("grupos", "array-contains-any", _grupos),
- );
- const querySnapshot = await getDocs(q);
- const docs = [];
- querySnapshot.forEach((doc) => {
- const data = doc.data();
- docs.push({
- grupos: data?.grupos,
- facebook: data?.facebook?.toLowerCase().trim(),
- twitterVerificado: data?.twitterVerificado ? true : false,
- facebookVerificado: data?.facebookVerificado ? true : false,
- instagramVerificado: data?.instagramVerificado ? true : false,
- twitter: data?.twitter?.toLowerCase().trim(),
- instagram: data?.instagram?.toLowerCase().trim(),
- telefono: data?.telefono,
- verificado: data?.verificado,
- nombre: data?.nombre,
- uid: data?.uid,
- id: doc.id,
- });
- });
- return docs;
- } catch (error) {
- console.log("error al obtener grupos: ", error);
- }
- };
- const abrirPublicacion = (e) => {
- window.open(e?.url, "_blank", "noopener,noreferrer");
- };
- const obtenerEnlaceYager = (e) => {
- const url = REACT_APP_WEB_URL + "evento-laud?id=" + e?.id;
- navigator.clipboard.writeText(url);
- message.info({
- content: "Se ha copiado el enlace al portapapeles.",
- });
- };
- const notificarNuevoEvento = async () => {
- try {
- setGuardando({ ...guardando, nuevo: true });
- const _usuarios = grupoEvento?.usuarios;
- const _redesEvento = grupoEvento?.redes;
- const plantilla = "nuevo_evento";
- if (_usuarios?.length < 1) {
- message.info("Este evento no ha sido procesado aún.");
- return;
- }
- const arrUsuarios = [];
- const eventoFb = _redesEvento.find((i) => i?.redSocial === "Facebook")
- ? true
- : false;
- const eventoIg = _redesEvento.find((i) => i?.redSocial === "Instagram")
- ? true
- : false;
- const eventoTw = _redesEvento.find((i) => i?.redSocial === "Twitter")
- ? true
- : false;
- const eventoTt = _redesEvento.find((i) => i?.redSocial === "TikTok")
- ? true
- : false;
- _usuarios?.forEach((u) => {
- const uid = u?.uid;
- let tieneFb = false;
- let tieneIg = false;
- let tieneTw = false;
- if (u?.facebookVerificado) tieneFb = true;
- if (u?.instagramVerificado) tieneIg = true;
- if (u?.twitterVerificado) tieneTw = true;
- const usuario = {
- uid,
- nombre: u?.nombre,
- telefono: u?.telefono,
- fb: eventoFb && tieneFb,
- ig: eventoIg && tieneIg,
- tw: eventoTw && tieneTw,
- tt: eventoTt /* && tieneTw */,
- };
- arrUsuarios.push(usuario);
- });
- const body = {
- idEvento: id,
- plantilla: plantilla,
- titulo: grupoEvento?.nombre,
- estatus: "Nuevo",
- enviado: null,
- fecha: new Date(),
- url: eventos.map((e) => `${REACT_APP_WEB_URL}evento-laud?id=${e?.id}`),
- urlFB: `${REACT_APP_WEB_URL}evento-laud?id=${eventos?.find((e) => e.redSocial === "Facebook")?.id}`,
- urlIG: `${REACT_APP_WEB_URL}evento-laud?id=${eventos?.find((e) => e.redSocial === "Instagram")?.id}`,
- urlTW: `${REACT_APP_WEB_URL}evento-laud?id=${eventos?.find((e) => e.redSocial === "Twitter")?.id}`,
- urlTT: `${REACT_APP_WEB_URL}evento-laud?id=${eventos?.find((e) => e.redSocial === "TikTok")?.id}`,
- usuarios: arrUsuarios,
- };
- if (!eventoFb) {
- body.urlFB = "";
- }
- if (!eventoIg) {
- body.urlIG = "";
- }
- if (!eventoTw) {
- body.urlTW = "";
- }
- if (!eventoTt) {
- body.urlTT = "";
- }
- // Buscamos si existe un registro con el ID del evento y la misma plantilla
- const q = firebaseQuery(
- collection(firestore, "notificaciones"),
- where("idEvento", "==", id),
- );
- const querySnapshot = await getDocs(q);
- let c = 0;
- querySnapshot.forEach((doc) => {
- if (doc.data().plantilla === plantilla) {
- c++;
- }
- });
- if (c > 0) {
- message.info("Ya hay un recordatorio de este evento.");
- return;
- }
- await addDoc(collection(firestore, "notificaciones"), body);
- message.success("Recordatorio enviado.");
- } catch (error) {
- message.error("Error al enviar la notificacion");
- console.log("error al notificar: ", error);
- } finally {
- setGuardando({ ...guardando, nuevo: false });
- }
- };
- const enviarRecordatorios = async () => {
- try {
- setGuardando({ ...guardando, faltante: true });
- const _usuarios = grupoEvento?.usuarios;
- const plantilla = "recordatorio";
- if (_usuarios?.length < 1) {
- message.info("Este evento no ha sido procesado aún.");
- return;
- }
- let eventoFb = null;
- let eventoTw = null;
- let eventoIg = null;
- let eventoTt = null;
- for (let i = 0; i < eventos.length; i++) {
- if (eventos[i].redSocial === "Facebook") {
- eventoFb = eventos[i];
- } else if (eventos[i].redSocial === "Instagram") {
- eventoIg = eventos[i];
- } else if (eventos[i].redSocial === "Twitter") {
- eventoTw = eventos[i];
- } else if (eventos[i].redSocial === "TikTok") {
- eventoTt = eventos[i];
- }
- }
- const arrUsuarios = [];
- _usuarios?.forEach((u) => {
- const uid = u?.uid;
- let tieneFb = false;
- let tieneIg = false;
- let tieneTw = false;
- if (u?.facebookVerificado) {
- tieneFb = true;
- }
- if (u?.instagramVerificado) {
- tieneIg = true;
- }
- if (u?.twitterVerificado) {
- tieneTw = true;
- }
- const usuario = {
- uid,
- nombre: u?.nombre,
- telefono: u?.telefono,
- fb: tieneFb && eventoFb?.resultado[uid]?.length === 0,
- ig: tieneIg && eventoIg?.resultado[uid]?.length === 0,
- tw: tieneTw && eventoTw?.resultado[uid]?.length === 0,
- tt: /* tieneTw && */eventoTt?.resultado[uid]?.length === 0,
- };
- /* if (!usuario.fb && !usuario.ig && !usuario.tw) {
- return true;
- } */
- arrUsuarios.push(usuario);
- });
- const body = {
- idEvento: id,
- plantilla: plantilla,
- titulo: grupoEvento?.nombre,
- estatus: "Nuevo",
- enviado: null,
- fecha: new Date(),
- urlFB: `${REACT_APP_WEB_URL}evento-laud?id=${eventos?.find((e) => e.redSocial === "Facebook")?.id}`,
- urlIG: `${REACT_APP_WEB_URL}evento-laud?id=${eventos?.find((e) => e.redSocial === "Instagram")?.id}`,
- urlTW: `${REACT_APP_WEB_URL}evento-laud?id=${eventos?.find((e) => e.redSocial === "Twitter")?.id}`,
- urlTT: `${REACT_APP_WEB_URL}evento-laud?id=${eventos?.find((e) => e.redSocial === "TikTok")?.id}`,
- usuarios: arrUsuarios,
- };
- if (!eventoFb) {
- body.urlFB = "";
- }
- if (!eventoIg) {
- body.urlIG = "";
- }
- if (!eventoTw) {
- body.urlTW = "";
- }
- if (!eventoTt) {
- body.urlTT = "";
- }
- // Buscamos si existe un registro con el ID del evento y la misma plantilla
- const q = firebaseQuery(
- collection(firestore, "notificaciones"),
- where("idEvento", "==", id),
- );
- const querySnapshot = await getDocs(q);
- let c = 0;
- querySnapshot.forEach((doc) => {
- if (doc.data().plantilla === plantilla) {
- c++;
- }
- });
- if (c > 0) {
- message.info("Ya hay un recordatorio de este evento.");
- return;
- }
- await addDoc(collection(firestore, "notificaciones"), body);
- message.success("Recordatorio guardado.");
- } catch (error) {
- message.error("Error al enviar notifiación.");
- console.log("error al enviar notifiacion: ", error);
- } finally {
- setGuardando({ ...guardando, faltante: false });
- }
- };
- const enviarFelicitacion = async () => {
- try {
- setGuardando({ ...guardando, felicitacion: true });
- const _usuarios = grupoEvento.usuarios;
- const plantilla = "evento_gracias";
- if (_usuarios?.length < 1) {
- message.info("Este evento no ha sido procesaod aún.");
- return;
- }
- let eventoFb = null;
- let eventoTw = null;
- let eventoIg = null;
- let eventoTt = null;
- for (let i = 0; i < eventos.length; i++) {
- if (eventos[i]?.redSocial === "Facebook") {
- eventoFb = eventos[i];
- } else if (eventos[i]?.redSocial === "Instagram") {
- eventoIg = eventos[i];
- } else if (eventos[i]?.redSocial === "Twitter") {
- eventoTw = eventos[i];
- } else if (eventos[i]?.redSocial === "TikTok") {
- eventoTt = eventos[i];
- }
- }
- const arrUsuarios = [];
- _usuarios?.forEach((u) => {
- const uid = u?.uid;
- let tieneFb = false;
- let tieneIg = false;
- let tieneTw = false;
- let cr = 0;
- if (u?.facebookVerificado) {
- tieneFb = true;
- cr = cr + 1;
- }
- if (u?.instagramVerificado) {
- tieneIg = true;
- cr = cr + 1;
- }
- if (u?.twitterVerificado) {
- tieneTw = true;
- cr = cr + 1;
- }
- const res =
- eventoFb?.resultado[uid].length +
- eventoIg?.resultado[uid].length +
- eventoTw?.resultado[uid].length +
- eventoTt?.resultado[uid].length;
- const usuario = {
- uid,
- nombre: u?.nombre,
- telefono: u?.telefono,
- fb: tieneFb && eventoFb?.resultado[uid]?.length > 0,
- ig: tieneIg && eventoIg?.resultado[uid]?.length > 0,
- tw: tieneTw && eventoTw?.resultado[uid]?.length > 0,
- tt: /* tieneTw && */eventoTw?.resultado[uid]?.length > 0,
- };
- // if( (res/cr) === 1 ) {
- arrUsuarios.push(usuario);
- // }
- });
- if (arrUsuarios?.length < 1) {
- message.info("No hay usuarios para notificar.");
- return;
- }
- const body = {
- idEvento: id,
- plantilla: plantilla,
- titulo: grupoEvento?.nombre,
- enviado: null,
- estatus: "Nuevo",
- fecha: new Date(),
- urlFB: `${REACT_APP_WEB_URL}evento-laud?id=${eventos?.find((e) => e.redSocial === "Facebook")?.id}`,
- urlIG: `${REACT_APP_WEB_URL}evento-laud?id=${eventos?.find((e) => e.redSocial === "Instagram")?.id}`,
- urlTW: `${REACT_APP_WEB_URL}evento-laud?id=${eventos?.find((e) => e.redSocial === "Twitter")?.id}`,
- urlTT: `${REACT_APP_WEB_URL}evento-laud?id=${eventos?.find((e) => e.redSocial === "TikTok")?.id}`,
- usuarios: arrUsuarios,
- };
- if (!eventoFb) {
- body.urlFB = "";
- }
- if (!eventoIg) {
- body.urlIG = "";
- }
- if (!eventoTw) {
- body.urlTW = "";
- }
- if (!eventoTt) {
- body.urlTT = "";
- }
- // Buscamos si existe un registro con el ID del evento y la misma plantilla
- const q = firebaseQuery(
- collection(firestore, "notificaciones"),
- where("idEvento", "==", id),
- );
- const querySnapshot = await getDocs(q);
- let c = 0;
- querySnapshot.forEach((doc) => {
- if (doc.data().plantilla === plantilla) {
- c++;
- }
- });
- if (c > 0) {
- message.info("Ya hay un recordatorio de este evento.");
- return;
- }
- await addDoc(collection(firestore, "notificaciones"), body);
- message.success("Recordatorio enviado.");
- } catch (error) {
- message.error("Error al enviar la notificacion");
- console.log("error al enviar felicitación: ", error);
- } finally {
- setGuardando({ ...guardando, felicitacion: false });
- }
- };
- const reporteCondesado = async () => {
- try {
- setGuardando({ ...guardando, condensado: true });
- // Obtener usuarios con sus redes sociales verificadas.
- const usuariosGrupo = await obtenerUsuariosGrupo();
- const eventos = [];
- const usuarios = [];
- const dataExcel = [];
- const fechas = formProcesar.getFieldValue("fechas");
- if (!fechas) {
- message.info("Debes de seleccionar un rango de fechas.");
- return;
- }
- const fechaInicio = new Date(fechas[0]?._d.setHours(0, 0, 0));
- const fechaFin = new Date(fechas[1]?._d.setHours(23, 59, 59));
- const queryConstraints = [
- where("timestamp", ">=", fechaInicio),
- where("timestamp", "<=", fechaFin),
- ];
- const ref = collection(firestore, "eventos");
- const q = firebaseQuery(
- ref,
- ...queryConstraints,
- orderBy("timestamp", "desc"),
- );
- const querySnapshot = await getDocs(q);
- // Crear arreglo de eventos.
- // * eventos []
- querySnapshot.forEach((doc) => {
- const data = doc.data();
- if (data?.estatus) {
- eventos.push({ ...data, id: doc.id });
- }
- });
- if (eventos.length < 1) {
- message.info("No hay eventos en el rango de fechas seleccionado.");
- return;
- }
- // Crear arreglo de usuarios.
- // * usuarios []
- usuariosGrupo.forEach((u) => {
- const tieneFb = u?.facebookVerificado ? 1 : 0;
- const tieneIg = u?.instagramVerificado ? 1 : 0;
- const tieneTw = u?.twitterVerificado ? 1 : 0;
- let usr = {
- uid: u?.uid,
- nombre: u?.nombre,
- tipo: `${tieneFb + tieneTw + tieneIg} RRSS`,
- redesActivas: tieneFb + tieneTw + tieneIg,
- tieneFb,
- tieneTw,
- tieneIg,
- facebook: tieneFb ? u?.facebook : "",
- instagram: tieneIg ? u?.instagram : "",
- twitter: tieneTw ? u?.twitter : "",
- verificado: u?.verificado !== "" ? "Verificado" : "",
- };
- usuarios.push(usr);
- });
- let columnasExcel = [
- { title: "UID", key: "uid" },
- { title: "Nombre", key: "nombre" },
- { title: "Tipo", key: "tipo" },
- { title: "Facebook", key: "facebook" },
- { title: "Instagram", key: "instagram" },
- { title: "Twitter", key: "twitter" },
- { title: "Verificado", key: "verificado" },
- ];
- // * columnasExcel []
- let totalEventos = {
- Twitter: 0,
- Facebook: 0,
- Instagram: 0,
- };
- eventos.forEach((e) => {
- const fecha = moment(e?.timestamp?.toDate()).format("DD-MM-YYYY");
- let red = "";
- if (e?.redSocial === "Twitter") {
- red = "TW";
- } else if (e?.redSocial === "Facebook") {
- red = "FB";
- } else if (e?.redSocial === "Instagram") {
- red = "INS";
- }
- totalEventos[e?.redSocial] += 1;
- columnasExcel.push({ title: `${red} - ${fecha}`, key: `${e?.id}` });
- });
- const usuariosExcel = [];
- let arrResultados = {};
- usuarios.forEach((u) => {
- const uid = u?.uid;
- columnasExcel.forEach((c) => {
- if (
- c?.key === "nombre" ||
- c?.key === "uid" ||
- c?.key === "tipo" ||
- c?.key === "facebook" ||
- c?.key === "instagram" ||
- c?.key === "twitter" ||
- c?.key === "verificado"
- )
- return true;
- if (!arrResultados[uid]) {
- arrResultados[uid] = {};
- }
- const evento = eventos?.find((e) => e?.id === c?.key);
- let flag = false;
- if (evento?.redSocial === "Instagram" && u?.tieneIg) {
- flag = true;
- }
- if (evento?.redSocial === "Facebook" && u?.tieneFb) {
- flag = true;
- }
- if (evento?.redSocial === "Twitter" && u?.tieneTw) {
- flag = true;
- }
- arrResultados[uid][c?.key] =
- flag && evento?.resultado[uid]?.length > 0 ? 1 : 0;
- });
- usuariosExcel.push({
- ...u,
- totalFb: u?.tieneFb && totalEventos.Facebook,
- totalTw: u?.tieneTw && totalEventos.Twitter,
- totalIg: u?.tieneIg && totalEventos.Instagram,
- });
- });
- // * return dataExcel []
- // Contamos participaciones (arreglo de usuarios)
- for (let i = 0; i < usuariosExcel.length; i++) {
- const resEvento = Object.keys(arrResultados[usuariosExcel[i]?.uid]).map(
- (key) => [key, arrResultados[usuariosExcel[i]?.uid][key]],
- );
- // Contamos
- let z = 0;
- for (let r = 0, l = resEvento?.length; r < l; r++) {
- z += arrResultados[usuariosExcel[i]?.uid][resEvento[r][0]];
- }
- const totalParticipacion =
- usuariosExcel[i]?.totalFb +
- usuariosExcel[i]?.totalIg +
- usuariosExcel[i]?.totalTw;
- const participacion = isNaN(z / totalParticipacion)
- ? 0
- : z / totalParticipacion;
- const obj = Object.assign(
- {
- ...usuariosExcel[i],
- participo: z,
- participaEn: totalParticipacion,
- participacion: participacion,
- },
- arrResultados[usuariosExcel[i]?.uid],
- );
- dataExcel.push(obj);
- }
- columnasExcel.push({ title: "Participando", key: "participaEn" });
- columnasExcel.push({ title: "Participó", key: "participo" });
- columnasExcel.push({ title: "Total", key: "participacion" });
- await excelCondensado(
- columnasExcel,
- dataExcel,
- totalEventos,
- eventos?.length,
- `Reporte condensado ${fechas[0].format("DD-MM-YYYY")}-${fechas[1].format("DD-MM-YYYY")}`,
- `Condensado de participación`,
- `Inicio: ${fechas[0].format("DD-MM-YYYY")} Fin:${fechas[1].format("DD-MM-YYYY")}`,
- "/LAUD-Logotipo.png",
- "",
- );
- } catch (error) {
- console.log("error al generar reporte consendado: ", error);
- } finally {
- setGuardando({ ...guardando, condensado: false });
- }
- };
- // Obtener grupo
- useEffect(() => {
- let mounted = true;
- if (mounted && editando) {
- try {
- setTimeout(async () => {
- const docRef = doc(firestore, "gruposEvento", id);
- const docSnap = await getDoc(docRef);
- setGrupoEvento(docSnap.data());
- }, 0);
- } catch (error) {
- console.log("error al obtener evento: ", error);
- } finally {
- setCargandoEvento(false);
- }
- }
- return () => (mounted = false);
- }, [editando, id]);
- // Obtener eventos del grupo
- useEffect(() => {
- let mounted = true;
- if (mounted && editando) {
- try {
- setTimeout(async () => {
- const q = firebaseQuery(
- collection(firestore, "eventos"),
- where("tag", "==", tag),
- );
- const querySnapshot = await getDocs(q);
- const docs = [];
- querySnapshot.forEach((doc) => {
- docs.push({
- ...doc.data(),
- id: doc.id,
- });
- });
- setEventos(docs);
- }, 0);
- } catch (error) {
- console.log("error al obtener evento: ", error);
- } finally {
- setCargandoEvento(false);
- }
- }
- return () => (mounted = false);
- }, [editando, tag]);
- useEffect(() => {
- let mounted = true;
- if (mounted && grupoEvento && editando) {
- setPreviaImg(grupoEvento?.pathFirebase);
- form.setFieldsValue({
- ...grupoEvento,
- fechaFinal: moment(grupoEvento?.fechaFinal),
- fechaInicio: moment(grupoEvento?.fechaInicio),
- });
- }
- return () => (mounted = false);
- }, [editando, grupoEvento, form]);
- if (cargandoEvento) return <ViewLoading />;
- return (
- <>
- {/* Modal Procesar */}
- <Modal
- title="Procesar"
- centered
- open={visible}
- okText="Procesar"
- confirmLoading={procesando}
- onOk={(e) => {
- if (textAreaData === "") {
- message.warning({
- content: "Atención: no dejar vacio",
- });
- return;
- }
- procesarUsuarios();
- guardarRegistro();
- }}
- onCancel={() => {
- setVisible(false);
- }}
- width={1000}
- >
- <Row>
- <Col span={24}>
- <TextArea
- onChange={(e) => setTextAreaData(e.target.value)}
- placeholder="Pegue el texto aqui"
- rows={6}
- />
- </Col>
- </Row>
- </Modal>
- {/* Modal Generar Reporte */}
- <Modal
- title="Generar Reporte"
- centered
- open={visibleReporte}
- okText="Generar Reporte"
- confirmLoading={procesando}
- onOk={(e) => {
- reporteCondesado();
- }}
- onCancel={() => {
- setVisibleReporte(false);
- }}
- okButtonProps={{ loading: guardando.condensado }}
- width={500}
- >
- <Row gutter={10} justify="center">
- <Col>
- {guardando.condensado && <Spin tip="Generando reporte..." />}
- </Col>
- <Col span={24} hidden={guardando.condensado}>
- <Form
- name="formProcesar"
- form={formProcesar}
- autoComplete="off"
- layout="vertical"
- >
- <Form.Item
- label="Selecciona un rango de fechas"
- name="fechas"
- required
- >
- <RangePicker style={{ width: "100%" }} format="DD-MM-YYYY" />
- </Form.Item>
- </Form>
- </Col>
- </Row>
- </Modal>
- <DefaultLayout multipleButtonData={buttons}>
- <Form name="form" form={form} autoComplete="off" layout="vertical">
- {/* Imagen - Nombre - Ciudad - Descripción - Url - Red social */}
- <Row gutter={10}>
- {/* Columna 1 */}
- <Col
- className="gutter-row"
- xs={{ span: 24 }}
- sm={{ span: 24 }}
- md={{ span: 8 }}
- lg={{ span: 8 }}
- >
- <Row
- gutter={10}
- style={{
- display: "flex",
- flexDirection: "row",
- height: "100%",
- }}
- >
- <Col span={24}>
- {previaImg ? (
- <img src={previaImg} width="100%" alt="" />
- ) : null}
- </Col>
- </Row>
- </Col>
- {/* Columna 2 */}
- <Col
- className="gutter-row"
- xs={{ span: 24 }}
- sm={{ span: 24 }}
- md={{ span: 16 }}
- lg={{ span: 16 }}
- >
- {/* Nombre evento - Ciuad */}
- <Row gutter={10}>
- <Col
- className="gutter-row"
- xs={{ span: 24 }}
- sm={{ span: 24 }}
- md={{ span: 12 }}
- lg={{ span: 12 }}
- >
- <Form.Item label="Nombre del evento" name="nombre">
- <Input readOnly />
- </Form.Item>
- </Col>
- <Col
- className="gutter-row"
- xs={{ span: 24 }}
- sm={{ span: 24 }}
- md={{ span: 12 }}
- lg={{ span: 12 }}
- >
- <Form.Item label="Ciudad" name="ciudad">
- <Input readOnly />
- </Form.Item>
- </Col>
- </Row>
- {/* Descripción */}
- <Row gutter={10}>
- <Col className="gutter-row" span={24}>
- <Form.Item label="Descripción" name="descripcion">
- <TextArea
- placeholder="Ingrese una descripción..."
- readOnly
- rows={4}
- />
- </Form.Item>
- </Col>
- </Row>
- </Col>
- </Row>
- {/* Fecha de inicio - Fecha fin - sin fecha - Accion */}
- <Row gutter={10} style={{ marginTop: 30 }}>
- <Col
- className="gutter-row"
- xs={{ span: 24 }}
- sm={{ span: 24 }}
- md={{ span: 8 }}
- lg={{ span: 8 }}
- >
- <Form.Item label="Fecha de inicio" name="fechaInicio">
- <DatePicker
- disabled
- format="YYYY-MM-DD HH:mm"
- style={{ width: "100%" }}
- locale={locale}
- showTime={{
- defaultValue: moment("00:00", "HH:mm"),
- }}
- />
- </Form.Item>
- </Col>
- <Col
- className="gutter-row"
- xs={{ span: 24 }}
- sm={{ span: 24 }}
- md={{ span: 8 }}
- lg={{ span: 8 }}
- >
- <Form.Item label="Fecha de finalización" name="fechaFinal">
- <DatePicker
- disabled
- format="YYYY-MM-DD HH:mm"
- style={{ width: "100%" }}
- locale={locale}
- showTime={{
- defaultValue: moment("00:00", "HH:mm"),
- }}
- />
- </Form.Item>
- </Col>
- <Col
- className="gutter-row"
- xs={{ span: 24 }}
- sm={{ span: 24 }}
- md={{ span: 8 }}
- lg={{ span: 8 }}
- >
- <Form.Item label="Acción" name="accion">
- <Select
- disabled
- mode="multiple"
- style={{ width: "100%" }}
- placeholder="Selecciona una o más opciones"
- optionLabelProp="label"
- >
- {acciones?.map((item) => (
- <Option
- value={item?.value}
- label={item?.label}
- key={item?.id}
- >
- <div className="demo-option-label-item">
- <span role="img" aria-label={item?.label}>
- {item?.icon}
- </span>
- {item?.label}
- </div>
- </Option>
- ))}
- </Select>
- </Form.Item>
- </Col>
- </Row>
- {/* Redes sociales */}
- <Row gutter={10}>
- {eventos.map((e, index) => (
- <Col
- key={`evento-${index}`}
- xs={{ span: 24 }}
- sm={{ span: 8 }}
- md={{ span: 8 }}
- lg={{ span: 8 }}
- >
- <Card
- style={{
- width: "100%",
- }}
- actions={[
- <Button
- type="text"
- onClick={() => {
- setVisible(true);
- setEvento(e);
- }}
- icon={<DeliveredProcedureOutlined />}
- >
- Procesar
- </Button>,
- <Button
- type="text"
- onClick={() =>
- history.push(
- urlweb + "/detalle?id=" + e?.id + "&tag=" + e?.tag,
- )
- }
- icon={<EditOutlined />}
- >
- Editar
- </Button>,
- <Button
- type="text"
- onClick={() =>
- history.push(
- urlweb +
- "/resultado-grupo-evento?id=" +
- e?.id +
- "&tag=" +
- e?.tag,
- )
- }
- icon={<BarChartOutlined />}
- >
- Resultados
- </Button>,
- ]}
- >
- <Meta
- avatar={<Avatar src={`/assets/${e?.redSocial}.png`} />}
- title={
- <Row gutter={10}>
- <Col>
- <Button onClick={() => abrirPublicacion(e)}>
- Abrir publicación
- </Button>
- </Col>
- <Col>
- <Button onClick={() => obtenerEnlaceYager(e)}>
- Enlace Laud
- </Button>
- </Col>
- </Row>
- }
- />
- </Card>
- </Col>
- ))}
- </Row>
- </Form>
- </DefaultLayout>
- </>
- );
- };
- export default EventoDetalleGrupo;
|