-
Form
{FormActual === 1 ? (
) : (
diff --git a/app/unbiters/profile/charts/Charts.js b/app/unbiters/profile/charts/Charts.js
new file mode 100644
index 0000000..68088a8
--- /dev/null
+++ b/app/unbiters/profile/charts/Charts.js
@@ -0,0 +1,296 @@
+"use client";
+import { useEffect, useState } from "react";
+import client from "@/config/client";
+import { ToastContainer, toast } from "react-toastify";
+import "react-toastify/dist/ReactToastify.css";
+import NotFoundChaza from "@/components/NotFound/NotFoundChaza";
+import { useUsers } from "@/context/UserContext";
+import Card from "@/components/Cards/Card";
+import Link from "next/link";
+import Cookies from "js-cookie";
+import ProfileUser from "@/components/Profile/ProfileUser";
+import LoadingPost from "@/components/Loading/LoadingPost";
+import React from 'react';
+import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js';
+import { Pie } from 'react-chartjs-2';
+import Container from "@/components/Container";
+import Banner from "@/components/Profile/Banner";
+
+ChartJS.register(ArcElement, Tooltip, Legend);
+
+const data = {
+ labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
+ datasets: [
+ {
+ label: '# of Votes',
+ data: [12, 19, 3, 5, 2, 3],
+ backgroundColor: [
+ 'rgba(255, 99, 132, 0.2)',
+ 'rgba(54, 162, 235, 0.2)',
+ 'rgba(255, 206, 86, 0.2)',
+ 'rgba(75, 192, 192, 0.2)',
+ 'rgba(153, 102, 255, 0.2)',
+ 'rgba(255, 159, 64, 0.2)',
+ ],
+ borderColor: [
+ 'rgba(255, 99, 132, 1)',
+ 'rgba(54, 162, 235, 1)',
+ 'rgba(255, 206, 86, 1)',
+ 'rgba(75, 192, 192, 1)',
+ 'rgba(153, 102, 255, 1)',
+ 'rgba(255, 159, 64, 1)',
+ ],
+ borderWidth: 1,
+ },
+ ],
+};
+export default function ChartsView({ chazasFetch }) {
+ const { userChazas, userData } = useUsers();
+
+ const notifyError = (error) =>
+ toast.error("Ups hay un problema! " + (error ? error : ""), {
+ position: "top-right",
+ autoClose: 5000,
+ hideProgressBar: false,
+ closeOnClick: true,
+ pauseOnHover: true,
+ draggable: true,
+ progress: undefined,
+ theme: "light",
+ });
+ const dataPersons = {
+ labels: ['Masculino', 'Femenino', 'Otros'],
+ datasets: [
+ {
+ label: 'Análisis por perspectiva de sexo ',
+ data: [3, 4, 1],
+ backgroundColor: [
+ 'rgba(255, 99, 132, 0.2)',
+ 'rgba(54, 162, 235, 0.2)',
+ 'rgba(153, 102, 255, 0.2)',
+ ],
+ borderColor: [
+ 'rgba(255, 99, 132, 1)',
+ 'rgba(54, 162, 235, 1)',
+ 'rgba(153, 102, 255, 1)',
+ ],
+ borderWidth: 2,
+ },
+ ],
+ };
+ const dataPersonsAge = {
+ nombreChaza: "CHaza",
+ labels: ['', 'Femenino', 'Otros'],
+ datasets: [
+ {
+ label: 'Análisis por perspectiva de edad ',
+ data: [3, 4, 1],
+ backgroundColor: [
+ 'rgba(255, 99, 132, 0.2)',
+ 'rgba(54, 162, 235, 0.2)',
+ 'rgba(153, 102, 255, 0.2)',
+ 'rgba(218, 247, 166, 0.2)',
+ 'rgba(45, 174, 215, 0.2)',
+ 'rgba(135, 102, 233, 0.2)',
+ ],
+ borderColor: [
+ 'rgba(255, 99, 132, 1)',
+ 'rgba(54, 162, 235, 1)',
+ 'rgba(153, 102, 255, 1)',
+ ],
+ borderWidth: 2,
+ },
+ ],
+ };
+ const [charts, setCharts] = useState([data, dataPersons, dataPersonsAge])
+ const [datasets, setDatasets] = useState([])
+ const [user, setUser] = useState("");
+ const [token, setToken] = useState("");
+ const [isLoading, setIsLoading] = useState(true);
+ const [chazas, setChaza] = useState([]);
+ const [id, setId] = useState("");
+ const [nombre, setNombre] = useState("");
+ const [fechaFundacion, setFechaFundacion] = useState("");
+ const [categorias, setCategorias] = useState("");
+ const [ubicacion, setUbicacion] = useState("");
+ const [descripcion, setDescripcion] = useState("");
+ const [horarioAtencion, setHorarioAtencion] = useState("");
+
+ useEffect(() => {
+ var tkn = Cookies.get("token");
+ setToken(tkn);
+ console.log(tkn)
+ setUser(JSON.parse(Cookies.get("user")))
+ if (userData.nivelSuscripcion == 1) {
+ try {
+ client.get("/publications/sexStats", {
+ headers: {
+ Authorization: `Bearer ${tkn}`,
+ },
+ }).then(res => {
+ var data = res.data.data.conteoChazas
+ //console.log(data)
+ var jsonData = []
+ for (var x = 0; x < data.length; x++) {
+ //console.log(data[x])
+ var masculino = data[x].conteoPorSexo.M
+ var femenino = data[x].conteoPorSexo.F
+ var otro = data[x].conteoPorSexo.Otro
+
+ var json = {
+ descripcion: "Con este análisis, podra examinar la participación por género en su chaza con el objetivo de comprender cómo diferentes géneros interactúan y contribuyen al ambiente y la clientela de esta.",
+ cantData: (masculino + femenino + otro),
+ nombreChaza: data[x].nombreChaza,
+ labels: ["Masculino", "Femenino", "Otro"],
+ datasets: [{
+ label: "Análisis por perspectiva de género",
+ data: [masculino, femenino, otro],
+ backgroundColor: [
+ 'rgba(255, 99, 132, 0.2)',
+ 'rgba(54, 162, 235, 0.2)',
+ 'rgba(153, 102, 255, 0.2)',
+ ],
+ borderWidth: 2,
+ }]
+ }
+ jsonData.push(json)
+ //setDatasets([...datasets, json])
+ }
+
+ client.get("/publications/ageStats", {
+ headers: {
+ Authorization: `Bearer ${tkn}`,
+ },
+ }).then(res => {
+ var data = res.data.data.conteoChazas
+ //console.log(data)
+ for (var x = 0; x < data.length; x++) {
+ console.log(x)
+ var menordieciocho = 0
+ var menortreinta = 0
+ var menorcuarentacinco = 0
+ var menorsesenta = 0
+ var menorsetentacinco = 0
+ var menornoventa = 0
+ var estadisticas = data[x].estadisticas
+ //console.log("estadisticas", estadisticas)
+ for (var i = 0; i < estadisticas.length; i++) {
+ console.log("estadisticas", estadisticas[i]._id)
+ if (estadisticas[i]._id == 18) {
+ menordieciocho = estadisticas[i].count
+ }
+ if (estadisticas[i]._id == 30) {
+ menortreinta = estadisticas[i].count
+ }
+ if (estadisticas[i]._id == 45) {
+ menorcuarentacinco = estadisticas[i].count
+ }
+ if (estadisticas[i]._id == 60) {
+ menorsesenta = estadisticas[i].count
+ }
+ if (estadisticas[i]._id == 75) {
+ menorsetentacinco = estadisticas[i].count
+ }
+ if (estadisticas[i]._id == "90+") {
+ menornoventa = estadisticas[i].count
+ }
+ }
+ var json = {
+ descripcion: "Este análisis tiene como objetivo permitirle examinar el perfil de edad de la clientela que opina sobre su chaza. Entender la distribución de edades puede proporcionar un panorama valioso sobre la dinámica de su clientela y orientar estrategias de marketing y experiencia del cliente.",
+ cantData: (menordieciocho + menortreinta + menorcuarentacinco + menorsesenta + menorsetentacinco + menornoventa),
+ nombreChaza: data[x].nombreChaza,
+ labels: ["Menor a 18 años", "Entre 19 años a 30 años ", "Entre 31 años a 45 años", "Entre 46 años a 60 años", "Entre 61 años a 75 años", "Mayor de 75 años"],
+ datasets: [{
+ label: "Análisis por perspectiva de edad",
+ data: [menordieciocho, menortreinta, menorcuarentacinco, menorsesenta, menorsetentacinco, menornoventa],
+ backgroundColor: [
+ 'rgba(255, 99, 132, 0.2)',
+ 'rgba(54, 162, 235, 0.2)',
+ 'rgba(153, 102, 255, 0.2)',
+ 'rgba(218, 247, 166, 0.2)',
+ 'rgba(255, 87, 51, 0.2)',
+ 'rgba(144, 12, 63, 0.2)',
+ ],
+ borderWidth: 2,
+ }]
+ }
+ jsonData.push(json)
+ //setDatasets([...datasets, json])
+ }
+ setDatasets((datasets) => [...datasets, ...jsonData]);
+ })
+ setIsLoading(false);
+ })
+ } catch (error) {
+ notifyError(error.response.data.message)
+ console.log(error.response)
+ }
+ } else {
+ notifyError("No tienes una subscripción premium, no puedes ver tus estadísticas.")
+
+ setIsLoading(false);
+ }
+ /*setNombre(userChazas.nombre);
+ setDescripcion(userChazas.descripcion);
+ setCategorias(userChazas.categorias);
+ setFechaFundacion(userChazas.fechaFundacion);
+ setUbicacion(userChazas.ubicacion);
+ setHorarioAtencion(userChazas.horarioAtencion);*/
+ }, []);
+ if (user.chaza && chazas.length == 0) {
+ //return
;
+ }
+ return (
+
+
+
+ {isLoading ? (
+
+ ) : (
+ <>
+
+ {
+ userData.nivelSuscripcion == 0 && userData.chaza ?
+ : null
+ }
+ {console.log(userData)}
+
+ {userData.nivelSuscripcion == 0 ?
+
:
+
+
+
+ {datasets.map((graph, idx) => (
+
+
+
{graph.datasets[0].label + " "} {"Chaza: " + graph.nombreChaza}
+
{graph.descripcion}
+ {graph.cantData == 0 ?
+
+
Ups, lo sentimos, aún no tenemos los datos suficientes para generar este reporte. Te invitamos a seguir opinando y hacerte más visible.
+
+ Ver publicaciones
+
+
+
+
:
+
}
+
+ ))
+
+ }
+
}
+
+ >
+ )}
+
+ );
+}
diff --git a/app/unbiters/profile/charts/page.js b/app/unbiters/profile/charts/page.js
new file mode 100644
index 0000000..f2cdd2f
--- /dev/null
+++ b/app/unbiters/profile/charts/page.js
@@ -0,0 +1,12 @@
+import ChartsView from "./Charts";
+
+
+function Charts() {
+ return (
+ <>
+
+ >
+ );
+}
+
+export default Charts;
diff --git a/app/unbiters/profile/comments/CommentContainer.js b/app/unbiters/profile/comments/CommentContainer.js
new file mode 100644
index 0000000..7a9989f
--- /dev/null
+++ b/app/unbiters/profile/comments/CommentContainer.js
@@ -0,0 +1,205 @@
+"use client";
+import { ToastContainer, toast } from "react-toastify";
+import "react-toastify/dist/ReactToastify.css";
+import CardReview from "@/components/Cards/CardReview";
+import NotFoundChaza from "@/components/NotFound/NotFoundChaza";
+import { myClient } from "@/config/client";
+import client from "@/config/client";
+import { useEffect, useState } from "react";
+import ModalComments from "@/components/Modal/ModalComments";
+import { useSearchParams, useRouter } from "next/navigation";
+import NewPost from "@/components/NewPost";
+import MyComments from "@/components/Cards/MyComments";
+import Cookies from "js-cookie";
+import { Suspense } from "react";
+import Container from "@/components/Container";
+import LoadingHome from "@/components/Loading/LoadingHome";
+import LoadingPost from "@/components/Loading/LoadingPost";
+import Banner from "@/components/Profile/Banner";
+
+import { useUsers } from "@/context/UserContext";
+async function loadPost() {
+ try {
+ var res = await client.get("chazas");
+ return res.data.data;
+ } catch (err) {
+ console.log("err", err);
+ }
+}
+function CommentsContainer() {
+
+ const { userChazas, userData } = useUsers();
+ const notifyEdit = () =>
+ toast.success("Actualizado con exito!", {
+ position: "top-right",
+ autoClose: 5000,
+ hideProgressBar: false,
+ closeOnClick: true,
+ pauseOnHover: true,
+ draggable: true,
+ progress: undefined,
+ theme: "light",
+ });
+ const notifyDelete = () =>
+ toast.success("Comentario eliminado!", {
+ position: "top-right",
+ autoClose: 5000,
+ hideProgressBar: false,
+ closeOnClick: true,
+ pauseOnHover: true,
+ draggable: true,
+ progress: undefined,
+ theme: "light",
+ });
+ const notifyError = () =>
+ toast.error("Ups hubo un error!", {
+ position: "top-right",
+ autoClose: 5000,
+ hideProgressBar: false,
+ closeOnClick: true,
+ pauseOnHover: true,
+ draggable: true,
+ progress: undefined,
+ theme: "light",
+ });
+ const [isLoading, setIsLoading] = useState(true);
+ const [comments, setComments] = useState([]);
+ const [token, setToken] = useState("");
+ const searchParams = useSearchParams();
+ const router = useRouter();
+ const idSearch = searchParams.get("id");
+ const [id, setId] = useState("");
+
+ useEffect(() => {
+ try {
+ var tkn = Cookies.get("token");
+ setToken(tkn);
+ client
+ .get("reviews/myReviews", {
+ headers: {
+ Authorization: `Bearer ${tkn}`,
+ },
+ })
+ .then((res) => {
+ var post = res.data.data.reviews;
+ console.log(post);
+ //console.log(post.length)
+ if (post.length != 0) {
+ setComments(post);
+ }
+ setIsLoading(false);
+ });
+ } catch (error) {
+ console.log(error);
+ }
+ }, []);
+
+ async function deleteCommentUp(id) {
+ console.log("borrarrrr", id)
+ console.log("editarr", token)
+ try {
+ const response = await client.delete(`reviews/${id}`, {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ });
+ console.log(response)
+ if (response.status == "204") {
+ //notifyDelete()
+ notifyDelete();
+ setComments((comments) => {
+ return comments.filter((post) => post.id !== id);
+ });
+ //router.refresh()
+ } else {
+ notifyError();
+ }
+ //console.log(response)
+ } catch (error) {
+ notifyError();
+ console.log(error);
+ }
+ }
+
+ async function editCommentUp(id, commentUp) {
+ //console.log("editarr", commentUp, id)
+ //console.log("editarr", token)
+ try {
+ const response = await client.patch(
+ `reviews/${id}`,
+ { review: commentUp },
+ {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ }
+ );
+ if (response.status == "200") {
+ //notifyDelete()
+ const newComments = comments.map((comment) => {
+ if (comment.id == id) {
+ comment.review = commentUp;
+ }
+ return comment;
+ });
+ notifyEdit();
+ setComments(newComments);
+ //console.log(comments)
+ //router.refresh()
+ } else {
+ notifyError();
+ }
+ //console.log(response)
+ } catch (error) {
+ notifyError();
+ console.log(error);
+ }
+ }
+
+ return (
+
+ {isLoading ? (
+
+ ) : (
+ <>
+ {
+ userData.nivelSuscripcion == 0 && userData.chaza ?
+ : null
+ }
+
+
+ {idSearch && (
+
{
+ router.push(`/unbiters/profile/posts/#${idSearch}`);
+ }}
+ _id={idSearch}
+ />
+ )}
+ {comments.length != 0 ? (
+
+ {comments.map((comment) => (
+
+ ))}
+
+ ) : (
+
+ )}
+ >
+ )}
+
+ );
+}
+
+export default CommentsContainer;
diff --git a/app/unbiters/profile/comments/page.js b/app/unbiters/profile/comments/page.js
index dd6baed..84cec43 100644
--- a/app/unbiters/profile/comments/page.js
+++ b/app/unbiters/profile/comments/page.js
@@ -1,180 +1,11 @@
-"use client";
-import { ToastContainer, toast } from "react-toastify";
-import "react-toastify/dist/ReactToastify.css";
-import CardReview from "@/components/Cards/CardReview";
-import NotFoundChaza from "@/components/NotFound/NotFoundChaza";
-import { myClient } from "@/config/client";
-import client from "@/config/client";
-import { useEffect, useState } from "react";
-import ModalComments from "@/components/Modal/ModalComments";
-import { useSearchParams, useRouter } from "next/navigation";
-import NewPost from "@/components/NewPost";
-import MyComments from "@/components/Cards/MyComments";
-import Cookies from "js-cookie";
-import Container from "@/components/Container";
+import { Suspense } from "react";
+import CommentsContainer from "./CommentContainer";
-async function loadPost() {
- try {
- var res = await client.get("chazas");
- return res.data.data;
- } catch (err) {
- console.log("err", err);
- }
-}
function Comments() {
- const notifyEdit = () =>
- toast.success("Actualizado con exito!", {
- position: "top-right",
- autoClose: 5000,
- hideProgressBar: false,
- closeOnClick: true,
- pauseOnHover: true,
- draggable: true,
- progress: undefined,
- theme: "light",
- });
- const notifyDelete = () =>
- toast.success("Comentario eliminado!", {
- position: "top-right",
- autoClose: 5000,
- hideProgressBar: false,
- closeOnClick: true,
- pauseOnHover: true,
- draggable: true,
- progress: undefined,
- theme: "light",
- });
- const notifyError = () =>
- toast.error("Ups hubo un error!", {
- position: "top-right",
- autoClose: 5000,
- hideProgressBar: false,
- closeOnClick: true,
- pauseOnHover: true,
- draggable: true,
- progress: undefined,
- theme: "light",
- });
- const [comments, setComments] = useState([]);
- const [token, setToken] = useState("");
- const searchParams = useSearchParams();
- const router = useRouter();
- const idSearch = searchParams.get("id");
- const [id, setId] = useState("");
- useEffect(() => {
- try {
- var tkn = Cookies.get("token");
- setToken(tkn);
- client
- .get("reviews/myReviews", {
- headers: {
- Authorization: `Bearer ${tkn}`,
- },
- })
- .then((res) => {
- var post = res.data.data.reviews;
- console.log(post);
- //console.log(post.length)
- if (post.length != 0) {
- setComments(post);
- }
- });
- } catch (error) {
- console.log(error);
- }
- }, []);
-
- async function deleteCommentUp(id) {
- //console.log("borrarrrr", id)
- try {
- const response = await client.delete(`reviews/${id}`, {
- headers: {
- Authorization: `Bearer ${token}`,
- },
- });
- if (response.status == "204") {
- //notifyDelete()
- notifyDelete();
- setComments((comments) => {
- return comments.filter((post) => post.id !== id);
- });
- //router.refresh()
- } else {
- notifyError();
- }
- //console.log(response)
- } catch (error) {
- notifyError();
- console.log(error);
- }
- }
- async function editCommentUp(id, commentUp) {
- //console.log("editarr", commentUp, id)
- //console.log("editarr", token)
- try {
- const response = await client.patch(
- `reviews/${id}`,
- { review: commentUp },
- {
- headers: {
- Authorization: `Bearer ${token}`,
- },
- }
- );
- if (response.status == "200") {
- //notifyDelete()
- const newComments = comments.map((comment) => {
- if (comment.id == id) {
- comment.review = commentUp;
- }
- return comment;
- });
- notifyEdit();
- setComments(newComments);
- //console.log(comments)
- //router.refresh()
- } else {
- notifyError();
- }
- //console.log(response)
- } catch (error) {
- notifyError();
- console.log(error);
- }
- }
return (
-
-
-
- {idSearch && (
-
{
- router.push(`/unbiters/profile/posts/#${idSearch}`);
- }}
- _id={idSearch}
- />
- )}
- {comments.length != 0 ? (
-
- {comments.map((comment) => (
-
- ))}
-
- ) : (
-
- )}
-
+ <>
+
+ >
);
}
diff --git a/app/unbiters/profile/community/page.js b/app/unbiters/profile/community/page.js
index 925285d..e902359 100644
--- a/app/unbiters/profile/community/page.js
+++ b/app/unbiters/profile/community/page.js
@@ -1,4 +1,6 @@
"use client";
+import "moment/locale/es";
+import moment from "moment";
import Cookies from "js-cookie";
import { useEffect, useState } from "react";
@@ -6,41 +8,30 @@ import { Tab } from "@headlessui/react";
import client from "@/config/client";
import { useUsers } from "@/context/UserContext";
import Container from "@/components/Container";
+import LoadingPost from "@/components/Loading/LoadingPost";
+import Banner from "@/components/Profile/Banner";
function classNames(...classes) {
return classes.filter(Boolean).join(" ");
}
export default function Community() {
- const { userChazas } = useUsers();
+ const { userChazas, userData } = useUsers();
+ const [isLoading, setIsLoading] = useState(true);
//console.log(userChazas)
const { _id } = userChazas;
const [reciente, setReciente] = useState([]);
let [categories] = useState({
- Reciente: [{}],
- Popular: [
- {
- id: 1,
- title: "Is tech making coffee better or worse?",
- date: "Jan 7",
- commentCount: 29,
- shareCount: 16,
- },
- {
- id: 2,
- title: "The most innovative things happening in coffee",
- date: "Mar 19",
- commentCount: 24,
- shareCount: 12,
- },
- ],
- //Comentarios: [{}],
+ Reciente: [],
+ Popular: [],
+ Comentarios: [],
});
useEffect(() => {
var token = Cookies.get("token");
var user = JSON.parse(Cookies.get("user"));
- console.log(user.id);
+ //console.log(user.id);
var chaza = null;
+ var chazaA = null;
client
.get("chazas/myChaza", {
headers: {
@@ -48,180 +39,223 @@ export default function Community() {
},
})
.then((res) => {
+ //console.log(res.data.data.myChaza);
chaza = res.data.data.myChaza[0];
- console.log(chaza);
- client
- .get(
- `publications/me/${chaza._id}`,
- {
- headers: {
- Authorization: `Bearer ${token}`,
+ chazaA = res.data.data.myChaza;
+ for (var i = 0; i < chazaA.length; i++) {
+ var body = {
+ filter: chazaA[i].nombre,
+ };
+ //console.log("body " + i, body);
+ client
+ .post(
+ `publications/searchPublication`,
+ body,
+ {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
},
- },
- { next: { revalidate: true | 0 | 60 } }
- )
- .then((res) => {
- console.log(res);
- if (!res.status == "200") {
- throw new Error("Failed to fetch data");
- }
- var commets = [];
- var data = res.data.data.data;
- if (data.length > 0) {
- console.log("daata ", data);
- for (var i = 0; i < data.length; i++) {
- client
- .get(
- `reviews/${data[0].id}`,
- {
- headers: {
- Authorization: `Bearer ${token}`,
- },
- },
- { next: { revalidate: true | 0 | 60 } }
- )
- .then((res) => {
- console.log(res);
- if (!res.status == "200") {
- throw new Error("Failed to fetch data");
- }
- var commets = res.data.data.data;
- if (data.length > 0) {
- categories.Comentarios = commets;
- } else {
- console.log("No hay data");
- }
- });
+ { next: { revalidate: true | 0 | 60 } }
+ )
+ .then((res) => {
+ if (!res.status == "200") {
+ throw new Error("Failed to fetch data");
}
- categories.Reciente = data;
- var popular = data.filter((item) => {
- if (item.likes > 0) {
- return item;
+ var data = res.data.data.data.hits;
+
+ //console.log("searchPublication ", data);
+ if (data.length > 0) {
+ //console.log(data)
+ categories.Reciente = categories.Reciente.concat(data);
+ var popular = categories.Reciente.filter((item) => {
+ if (item.likes > 0) {
+ return item;
+ }
+ });
+ if (popular.length == 0) {
+ popular = categories.Reciente;
}
- });
- categories.Popular = popular;
- setReciente(data);
- } else {
- console.log("No hay data");
- }
- });
+ categories.Popular = popular;
+ setReciente(data);
+ setIsLoading(false);
+ for (var i = 0; i < data.length; i++) {
+ var idP = data[i].id;
+ client
+ .get(
+ `reviews/${idP}`,
+ {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ },
+ { next: { revalidate: true | 0 | 60 } }
+ )
+ .then((response) => {
+ if (!response.status == "200") {
+ throw new Error("Failed to fetch data");
+ }
+ var commets = response.data.data.data;
+ if (commets.length > 0) {
+ console.log("comme", commets);
+ categories.Comentarios =
+ categories.Comentarios.concat(
+ commets
+ );
+ } else {
+ console.log("No hay data");
+ }
+ });
+ }
+ } else {
+ console.log("No hay data");
+ setIsLoading(false);
+ }
+ });
+ }
});
}, []);
return (
<>
- {reciente.length != 0 ? (
-
-
-
- {Object.keys(categories).map((category) => (
-
- classNames(
- "w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-neutral-900",
- "ring-white/60 ring-offset-2 ring-offset-white focus:outline-none focus:ring-2",
- selected
- ? "bg-red-400 shadow text-white"
- : "text-neutral-100 hover:bg-red-400/[0.5] "
- )
- }
- >
- {category}
-
- ))}
-
-
- {console.log(categories)}
- {Object.values(categories).map((posts, idx) => (
-
- {posts.length != 0 ? (
-
- {console.log(idx)}
- {posts.map((post) => (
-
-
- {idx != 2
- ? post.texto
- : post.review}
-
+ {isLoading ? (
+
+ ) : (
+ <>
+ {userData.nivelSuscripcion == 0 && userData.chaza ? (
+
+ ) : null}
+ {reciente.length != 0 ? (
+
+
+
+ {Object.keys(categories).map((category) => (
+
+ classNames(
+ "w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-neutral-900",
+ "ring-white/60 ring-offset-2 ring-offset-white focus:outline-none focus:ring-2",
+ selected
+ ? "bg-red-400 shadow text-white"
+ : "text-neutral-100 hover:bg-red-400/[0.5] "
+ )
+ }
+ >
+ {category}
+
+ ))}
+
+
+ {console.log(categories)}
+ {Object.values(categories).map((posts, idx) => (
+
+ {console.log(posts)}
+ {posts.length != 0 ? (
+
+ {posts.map((post) => (
+
+
+ {idx != 2
+ ? post.texto
+ : post.review}
+
-
-
- {idx != 2
- ? "hoy"
- : post.createdAt}
-
- {idx != 2 ? (
- ·
- ) : null}
-
- {idx != 2
- ? post.numComentarios +
- " comentarios"
- : null}{" "}
-
- {idx != 2 ? (
- ·
- ) : null}
-
- {idx != 2
- ? post.likes + " me gusta"
- : null}
-
- {idx != 2 ? (
- ·
- ) : null}
-
- {idx != 2
- ? post.rating +
- " estrellas"
- : null}{" "}
-
-
+
+
+ {idx != 2
+ ? moment(
+ post.createdAt,
+ "YYYYMMDD"
+ ).format("LL")
+ : moment(
+ post.createdAt,
+ "YYYYMMDD"
+ ).format("LL")}
+
+ {idx != 2 ? (
+ ·
+ ) : null}
+
+ {idx != 2
+ ? post.numComentarios +
+ " comentarios"
+ : null}{" "}
+
+ {idx != 2 ? (
+ ·
+ ) : null}
+
+ {idx != 2
+ ? post.likes +
+ " me gusta"
+ : null}
+
+ {idx != 2 ? (
+ ·
+ ) : null}
+
+ {idx != 2
+ ? post.rating +
+ " estrellas"
+ : null}{" "}
+
+
-
-
- ))}
-
- ) : (
-
- )}
-
- ))}
-
-
-
- ) : (
-
-
-
+
+
+ ))}
+
+ ) : (
+
+ )}
+
+ ))}
+
+
+
+ ) : (
+
+
+
+ )}
+ >
)}
>
);
diff --git a/app/unbiters/profile/layout.js b/app/unbiters/profile/layout.js
index 9f95683..7d27d81 100644
--- a/app/unbiters/profile/layout.js
+++ b/app/unbiters/profile/layout.js
@@ -1,40 +1,44 @@
+import NavbarProfile from "@/components/NavbarProfile";
+import UploadImage from "@/components/Forms/UploadImage";
+import client from "@/config/client";
+import Image from "next/image";
+import { Suspense } from "react";
-import NavbarProfile from '@/components/NavbarProfile';
-import UploadImage from '@/components/Forms/UploadImage';
-import client from "@/config/client"
-import Image from 'next/image';
-
-import '@/styles/profile.css';
-import Navbar from '@/components/Navbar/Navbar';
+import "@/styles/profile.css";
+import Navbar from "@/components/Navbar/Navbar";
+import LoadingHome from "@/components/Loading/LoadingHome";
+import Banner from "@/components/Profile/Banner";
export default function ProfileLayout({ children }) {
return (
- <>
-
-
+
+
+ data-modal-target="upload"
+ data-modal-toggle="upload"
+ >
-
-
-
+ src="/images/logo.png"
+ >
{/* */}
+
{children}
- >
- )
-}
\ No newline at end of file
+
+ );
+}
diff --git a/app/unbiters/profile/me/page.js b/app/unbiters/profile/me/page.js
index 5e22cea..6146f32 100644
--- a/app/unbiters/profile/me/page.js
+++ b/app/unbiters/profile/me/page.js
@@ -38,5 +38,5 @@ export default async function ProfileView() {
//const chazas = await loadChazas(token);
//const names = await loadNames();
//console.log(names)
- return (
)
+ return (
)
}
diff --git a/app/unbiters/profile/page.js b/app/unbiters/profile/page.js
index 64c73bf..dd2e029 100644
--- a/app/unbiters/profile/page.js
+++ b/app/unbiters/profile/page.js
@@ -33,7 +33,6 @@ export default async function ProfileView() {
const cookieStore = cookies();
const token = cookieStore.get("token").value;
const user = JSON.parse(cookieStore.get("user").value);
- console.log((user).chaza)
const chazas = await loadChazas(token);
//const names = await loadNames();
//console.log(names)
diff --git a/app/unbiters/register/page.js b/app/unbiters/register/page.js
index 3c4620c..89e0612 100644
--- a/app/unbiters/register/page.js
+++ b/app/unbiters/register/page.js
@@ -1,16 +1,43 @@
"use client";
+import { ToastContainer, toast } from "react-toastify";
+import "react-toastify/dist/ReactToastify.css";
import Image from "next/image";
+import Cookies from "js-cookie";
import Link from "next/link";
import { Button } from "flowbite-react";
import client from "@/config/client";
import React, { useState } from "react";
+import { useUsers } from "@/context/UserContext";
import { useRouter } from "next/navigation";
-import DatePicker from "react-datepicker";
+import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
export default function Register() {
- const { push } = useRouter();
+ const notifySucces = (name) =>
+ toast.success(name + " Bienvenido a UNBiters!", {
+ position: "top-right",
+ autoClose: 5000,
+ hideProgressBar: false,
+ closeOnClick: true,
+ pauseOnHover: true,
+ draggable: true,
+ progress: undefined,
+ theme: "light",
+ });
+ const notifyError = (error) =>
+ toast.error("Ups hay un problema! " + (error ? error : ""), {
+ position: "top-right",
+ autoClose: 5000,
+ hideProgressBar: false,
+ closeOnClick: true,
+ pauseOnHover: true,
+ draggable: true,
+ progress: undefined,
+ theme: "light",
+ });
+ const { setLogin, setUser, setChazas, setIsToken } = useUsers();
+ const router = useRouter();
const [errors, setErrors] = useState([]);
const [nombre, setNombre] = useState("");
const [sexo, setSexo] = useState("");
@@ -27,7 +54,15 @@ export default function Register() {
const handleSubmit = async (e) => {
e.preventDefault();
if (!terms) {
- setErrors(["Debes aceptar los términos y condiciones para registrarte."]);
+ notifyError("Debes aceptar los términos y condiciones para registrarte.")
+ //setErrors(["Debes aceptar los términos y condiciones para registrarte."]);
+ return
+ }
+ console.log("fechaNacimiento ", fechaNacimiento);
+ if (fechaNacimiento == null) {
+ notifyError("Por favor proporciona tu fecha de nacimiento.")
+ //setErrors(["Debes aceptar los términos y condiciones para registrarte."]);
+ return
}
try {
var body = {
@@ -39,31 +74,42 @@ export default function Register() {
chaza: chaza == "on" ? true : false,
fechaNacimiento
};
- console.log(body);
const response = await client.post("users/signup", body);
console.log("request ", response);
if (response.data.status === "success") {
+
+ setLogin(true);
const { token } = response.data;
- const { nombre, sexo, _id, chaza, fechaNacimiento } = response.data.data.user;
+ setIsToken(token)
+ const { user, chaza } = response.data.data;
+ const { nombre, _id, cliente, nivelSuscripcion } =
+ response.data.data.user;
+ //setUser(user);
+ //setChazas(chaza);
+ Cookies.set("token", token);
+ Cookies.set("user", JSON.stringify(user));
+ window.sessionStorage.setItem("user", user);
window.sessionStorage.setItem("token", token);
window.sessionStorage.setItem("nombre", nombre);
- window.sessionStorage.setItem("sexo", sexo);
window.sessionStorage.setItem("id", _id);
window.sessionStorage.setItem("sesion", "true");
- window.sessionStorage.setItem("fechaNacimiento", fechaNacimiento);
- if (chaza) {
- window.sessionStorage.setItem("chaza", "true");
- } else {
- window.sessionStorage.setItem("chaza", "false");
- }
- push("/unbiters/profile");
+ window.sessionStorage.setItem("cliente", cliente);
+ window.sessionStorage.setItem("nivelSuscripcion", nivelSuscripcion);
+ router.push("/unbiters/profile", undefined, { shallow: false });
+ notifySucces(nombre)
}
+
+ setTimeout(function () {
+ setErrors("");
+ }, 5000);
} catch (err) {
console.log("log al registrarte", err);
var error = err.response.data.error;
- console.error("Error al registrarte", err.response.data);
- setErrors([error]);
+
+ notifyError(err.response.data.message)
+ console.error("Error al registrarte", err.response.data.message);
+ //setErrors([error]);
}
};
@@ -77,54 +123,56 @@ export default function Register() {
minHeight: "100vh",
}}
>
-
+
+
- {!errors
+ {console.log(errors)}
+ {errors.length != 0
? errors.map((err) => (
-
+
+
+
+
Info
+
+ {err}
+
+
+ Close
-
+
- Info
-
- {err.message}
-
-
- Close
-
-
-
-
-
- ))
+
+
+ ))
: null}
@@ -172,9 +220,9 @@ export default function Register() {
Selecciona una opción
-
Masculino
-
Femenino
-
Otro
+
Masculino
+
Femenino
+
Otro
@@ -182,6 +230,7 @@ export default function Register() {
setFechaNacimiento(date)}
@@ -191,6 +240,7 @@ export default function Register() {
isClearable
showYearDropdown
scrollableYearDropdown
+ maxDate={new Date("12-31-2005")}
/>
diff --git a/components/About/Values.js b/components/About/Values.js
index 47fcb6c..0194b43 100644
--- a/components/About/Values.js
+++ b/components/About/Values.js
@@ -1,133 +1,267 @@
-import Image from "next/image"
-
+import Image from "next/image";
+import Link from "next/link";
export default function Values() {
const team = [
{
- "id": "1",
- "nombre": "Andrés Felipe López Gutiérrez",
- "cargo": "Desarrollador Frontend Junior",
- "description": "Estoy perfeccionando mis habilidades y aumentando mis conociminetos día a día :D",
- "facebook": "https://web.facebook.com/andres.lopezgutierrez.94/",
- "linkedin": "https://www.linkedin.com/in/anlopezgu/",
- "github": "https://github.com/anlopezgu",
- "url": "/images/Andrelo.jpg"
+ id: "1",
+ nombre: "Andrés Felipe López Gutiérrez",
+ cargo: "Desarrollador Frontend Junior",
+ description:
+ "Estoy perfeccionando mis habilidades y aumentando mis conociminetos día a día :D",
+ facebook: "https://web.facebook.com/andres.lopezgutierrez.94/",
+ linkedin: "https://www.linkedin.com/in/anlopezgu/",
+ github: "https://github.com/anlopezgu",
+ url: "/images/Andrelo.jpg",
},
{
- "id": "2",
- "nombre": "John Jairo Riaño Martinez",
- "cargo": "Desarrollador FullStack",
- "description": "Cuento con habildades en desarrollo de Frontend con tecnologias como ReactJS, NextJS",
- "facebook": "ada",
- "linkedin": "",
- "github": "",
- "url": "/images/1697919953864.jpg"
+ id: "2",
+ nombre: "John Jairo Riaño Martinez",
+ cargo: "Desarrollador FullStack",
+ description:
+ "Cuento con habildades en desarrollo de Frontend con tecnologias como ReactJS, NextJS",
+ facebook: "https://www.facebook.com/jhonjairo.rianomartinez.3?mibextid=ZbWKwL",
+ linkedin: "https://www.linkedin.com/in/jorianom/",
+ github: "https://github.com/jorianom",
+ url: "/images/1697919953864.jpg",
},
{
- "id": "3",
- "nombre": "David Stiven Poveda Tabirda",
- "cargo": "Desarrollador Backend",
- "description": "Cuento con habildades en desarrollo de Backend con NodeJS, Django. Manejo bases de datos especializadas en NoSQL pero tambien trabjo en tecnologias como MySQL y PostgresSQL. Soy un programador en constante busqueda de nuevas herramientas!",
- "facebook": "https://www.facebook.com/davidstiven.povedat/",
- "linkedin": "https://www.linkedin.com/in/david-stiven-poveda-taborda-521ab7207/",
- "github": "https://github.com/Dapstab",
- "url": "/images/12311421.jpg"
+ id: "3",
+ nombre: "David Stiven Poveda Tabirda",
+ cargo: "Desarrollador Backend",
+ description:
+ "Cuento con habildades en desarrollo de Backend con NodeJS, Django. Manejo bases de datos especializadas en NoSQL pero tambien trabjo en tecnologias como MySQL y PostgresSQL. Soy un programador en constante busqueda de nuevas herramientas!",
+ facebook: "https://www.facebook.com/davidstiven.povedat/",
+ linkedin:
+ "https://www.linkedin.com/in/david-stiven-poveda-taborda-521ab7207/",
+ github: "https://github.com/Dapstab",
+ url: "/images/12311421.jpg",
},
{
- "id": "4",
- "nombre": "Gian Emanuel Morales González",
- "cargo": "Desarrollador Frontend",
- "description": "Cuento con habilidades en desarrollo de Frontend en Frameworks como NextJS, Vue o tailwindCSS",
- "facebook": "",
- "linkedin": "https://www.linkedin.com/in/gmoralesg/",
- "github": "https://github.com/gimoralesg",
- "url": "/images/gemgpfp.jpg"
-
- }
- ]
+ id: "4",
+ nombre: "Gian Emanuel Morales González",
+ cargo: "Desarrollador Frontend",
+ description:
+ "Cuento con habilidades en desarrollo de Frontend en Frameworks como NextJS, Vue o tailwindCSS",
+ facebook: "",
+ linkedin: "https://www.linkedin.com/in/gmoralesg/",
+ github: "https://github.com/gimoralesg",
+ url: "/images/gemgpfp.jpg",
+ },
+ ];
return (
-
- Visión
- Ser la plataforma líder de la Universidad Nacional de Colombia sede Bogotá en promover la calidad y transparencia de nuestros servicios, y en un plazo de dos años, expandirnos a otras sedes a nivel nacional.
+
+ Visión
+
+
+ Ser la plataforma líder de la Universidad Nacional de Colombia
+ sede Bogotá en promover la calidad y transparencia de nuestros
+ servicios, y en un plazo de dos años, expandirnos a otras sedes a
+ nivel nacional.
+
- Misión
- Dar a conocer la opinión de las chazas en la Universidad Nacional de Colombia sede Bogotá. A través de un foro web en el que la comunidad universitaria califica y reseñan sus experiencias, permitiendo a propietarios mejorar la calidad de sus servicios.
+
+ Misión
+
+
+ Dar a conocer la opinión de las chazas en la Universidad Nacional
+ de Colombia sede Bogotá. A través de un foro web en el que la
+ comunidad universitaria califica y reseñan sus experiencias,
+ permitiendo a propietarios mejorar la calidad de sus servicios.
+
- Nuestros valores
- Nuestro equipo se destaca por su flexibilidad, empatia, sinceridad y colaboración.
+
+ Nuestros valores
+
+
+ Nuestro equipo se destaca por su flexibilidad, empatia, sinceridad
+ y colaboración.
+
- Nuestro equipo
- El equipo de UNBiters está formado por un grupo de apasionados por el desarrollo que están comprometidos a mejorar como grupo e individualmente en el desarrollo profesional.
+
+ Nuestro equipo
+
+
+ {" "}
+ El equipo de UNBiters está formado por un grupo de apasionados por
+ el desarrollo que están comprometidos a mejorar como grupo e
+ individualmente en el desarrollo profesional.
- {team ? team.map((tea) => (
-
-
-
- {tea.url != "" ?
-
- : null}
-
-
-
-
{tea.cargo}
-
{tea.description}
-
- {tea.facebook != "" ?
-
-
-
-
-
- : null}
- {tea.linkedin != "" ?
-
-
-
-
-
- : null}
- {tea.github != "" ?
-
-
-
-
-
- : null}
-
-
-
- )) : null}
+ {team
+ ? team.map((tea) => (
+
+
+ {tea.url != "" ? (
+
+ ) : null}
+
+
+
+
+ {tea.cargo}
+
+
+ {tea.description}
+
+
+ {tea.facebook != "" ? (
+
+
+
+
+
+
+
+ ) : null}
+ {tea.linkedin != "" ? (
+
+
+
+
+
+
+
+ ) : null}
+ {tea.github != "" ? (
+
+
+
+
+
+
+
+ ) : null}
+
+
+
+ ))
+ : null}
- Nuestros Colores
- #FFD31D: El amarillo brillante está asociado con la energía, la felicidad y la positividad. En el contexto de comida, el amarillo puede evocar sensaciones de sabor y frescura, siendo un color atractivo para resaltar platos y productos alimenticios.
- #D63447: El rojo cereza es un tono de rojo profundo que sugiere pasión, apetito y energía. En la industria alimentaria, el rojo a menudo se asocia con la tentación y puede estimular el apetito, haciéndolo un color atractivo para resaltar platillos o productos de comida.
- #F57B51: El melocotón es un tono suave de naranja que transmite calidez, frescura y apertura. En la comida, el melocotón puede evocar sabores frutales y naturales, siendo un color acogedor para entornos relacionados con alimentos y bebidas.
- #F6EEDF:: El blanco roto es un tono suave y cálido de blanco que transmite pureza, limpieza y simplicidad. En el contexto de la comida, el blanco roto puede utilizarse para resaltar la frescura y la calidad de los ingredientes, así como para crear una sensación de limpieza y profesionalismo en el entorno alimentario.
+
+ Nuestros Colores
+
+
+ {" "}
+ #FFD31D: El
+ amarillo brillante está asociado con la energía, la felicidad y la
+ positividad. En el contexto de comida, el amarillo puede evocar
+ sensaciones de sabor y frescura, siendo un color atractivo para
+ resaltar platos y productos alimenticios.
+
+
+ {" "}
+ #D63447: El rojo
+ cereza es un tono de rojo profundo que sugiere pasión, apetito y
+ energía. En la industria alimentaria, el rojo a menudo se asocia
+ con la tentación y puede estimular el apetito, haciéndolo un color
+ atractivo para resaltar platillos o productos de comida.
+
+
+ {" "}
+ #F57B51: El
+ melocotón es un tono suave de naranja que transmite calidez,
+ frescura y apertura. En la comida, el melocotón puede evocar
+ sabores frutales y naturales, siendo un color acogedor para
+ entornos relacionados con alimentos y bebidas.
+
+
+ {" "}
+ #F6EEDF:: El
+ blanco roto es un tono suave y cálido de blanco que transmite
+ pureza, limpieza y simplicidad. En el contexto de la comida, el
+ blanco roto puede utilizarse para resaltar la frescura y la
+ calidad de los ingredientes, así como para crear una sensación de
+ limpieza y profesionalismo en el entorno alimentario.
+
+
+
+
+
+ Nuestras politicas
+
+
+ {" "}
+ Para UNBiters es muy importante que sepas cómo funcionamos. A
+ continuación, te proporcionamos toda la{" "}
+
+ información legal
+ {" "}
+ y{" "}
+
+ nuestros términos y condiciones
+
+ .
+
-
- )
+ );
}
diff --git a/components/Cards/Card.js b/components/Cards/Card.js
index bd6a75d..325cc8d 100644
--- a/components/Cards/Card.js
+++ b/components/Cards/Card.js
@@ -1,22 +1,57 @@
"use client";
+import { v4 as uuidv4 } from "uuid";
import Link from "next/link";
+import { ToastContainer, toast } from "react-toastify";
+import "react-toastify/dist/ReactToastify.css";
import { useRouter } from "next/navigation";
import Image from "next/image";
+import client from "@/config/client";
import Delete from "../Modal/Delete";
import { useState } from "react";
-export default function Card({ className, card, comments, idModal, mode }) {
+export default function Card({
+ setChaza,
+ token,
+ className,
+ card,
+ comments,
+ idModal,
+ mode,
+}) {
//console.log(card.redesSociales[0])
-
+ const notifyDelete = () =>
+ toast.success("Publicación eliminada!", {
+ position: "top-right",
+ autoClose: 5000,
+ hideProgressBar: false,
+ closeOnClick: true,
+ pauseOnHover: true,
+ draggable: true,
+ progress: undefined,
+ theme: "light",
+ });
+ const notifyError = () =>
+ toast.error("Ups hubo un error!", {
+ position: "top-right",
+ autoClose: 5000,
+ hideProgressBar: false,
+ closeOnClick: true,
+ pauseOnHover: true,
+ draggable: true,
+ progress: undefined,
+ theme: "light",
+ });
const [isOpenDelete, setIsOpenDelete] = useState(false);
const router = useRouter();
+ console.log(card)
var src = "/images/test.jpg";
- if (card.imagenUrl) {
- src = card.imagenUrl;
+ if (card.imagenId) {
+ var url = card.imagenUrl.split("upload/")
+ src = url[0] + "upload/c_scale,h_300,w_500/" + url[1];
}
async function deleteChaza(id) {
- console.log("borrado");
+ console.log("borrado", token);
try {
const response = await client.delete(`chazas/deleteMyChaza/${card.id}`, {
headers: {
@@ -31,6 +66,13 @@ export default function Card({ className, card, comments, idModal, mode }) {
return comments.filter(post => post.id !== id)
})*/
//router.refresh()
+ var res = await client.get("chazas/myChaza", {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ });
+ //console.log(res.data.data)
+ setChaza(res.data.data.myChaza);
} else {
notifyError();
}
@@ -42,6 +84,7 @@ export default function Card({ className, card, comments, idModal, mode }) {
}
return (
+
{isOpenDelete && (
*/}
-
-
-
{card.redesSociales
? card.redesSociales.map((redesSociales) => (
-
-
- {redesSociales}
-
-
- ))
+
+
+ {redesSociales}
+
+
+ ))
: null}
@@ -273,39 +295,29 @@ export default function Card({ className, card, comments, idModal, mode }) {
{card.mediosPagos
? card.mediosPagos.map((mediosPagos) => (
-
-
- {mediosPagos}
-
-
- ))
+
+
+ {mediosPagos}
+
+
+ ))
: null}
- {card.categorias
- ? card.categorias.map((categorias) => (
-
- #{categorias}
-
- ))
+ {card.tags
+ ? card.tags.map((categorias) => (
+
+ #{categorias}
+
+ ))
: null}
diff --git a/components/Cards/CardProfile.js b/components/Cards/CardProfile.js
index a4d2e80..923b388 100644
--- a/components/Cards/CardProfile.js
+++ b/components/Cards/CardProfile.js
@@ -5,11 +5,19 @@ import NotFoundChaza from "@/components/NotFound/NotFoundChaza";
import { useUsers } from "@/context/UserContext";
import Card from "@/components/Cards/Card";
import Link from "next/link";
+import Cookies from "js-cookie";
+import { useRouter } from "next/navigation";
import ProfileUser from "../Profile/ProfileUser";
+import LoadingPost from "../Loading/LoadingPost";
+import Banner from "../Profile/Banner";
+import Delete from "../Modal/Delete";
-export default function CardProfile({ chazasFetch, user }) {
- const { userChazas } = useUsers();
-
+export default function CardProfile({ chazasFetch }) {
+ const { setLogin, userData, setIsToken } = useUsers();
+ console.log(userData)
+ const [user, setUser] = useState("");
+ const [token, setToken] = useState("");
+ const [isLoading, setIsLoading] = useState(true);
const [chazas, setChaza] = useState([]);
const [id, setId] = useState("");
const [nombre, setNombre] = useState("");
@@ -18,43 +26,161 @@ export default function CardProfile({ chazasFetch, user }) {
const [ubicacion, setUbicacion] = useState("");
const [descripcion, setDescripcion] = useState("");
const [horarioAtencion, setHorarioAtencion] = useState("");
+ const [isOpenDelete, setIsOpenDelete] = useState(false);
+ const [isOpenDesactivar, setIsOpenDesactivar] = useState(false);
+
+ const router = useRouter();
+ const desactivar = async () => {
+
+ const res = await client.get(`payment/mySubscription`, {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ });
+ console.log(res);
+ if (res.status == "200") {
+ const idSus = res.data.data.subscription.id
+
+ const response = await client.patch(`payment/subscription/${idSus}`, {}, {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ });
+
+ console.log(response);
+ if (response.status == "200") {
+
+ setIsToken(null)
+ Cookies.remove("token", { path: "/" });
+ Cookies.remove("user");
+ window.sessionStorage.clear();
+ setLogin(false);
+ router.push("/unbiters/login");
+ }
+ }
+ }
+ const deleteCuenta = async () => {
+ }
useEffect(() => {
- setChaza(chazasFetch);
+
+ var tkn = Cookies.get("token");
+ setToken(tkn);
+ console.log(tkn)
+ setUser(JSON.parse(Cookies.get("user")))
+ client.get("chazas/myChaza", {
+ headers: {
+ Authorization: `Bearer ${tkn}`,
+ },
+ }).then(res => {
+ res.data.data.myChaza
+ setChaza(res.data.data.myChaza);
+ setIsLoading(false);
+ })
/*setNombre(userChazas.nombre);
setDescripcion(userChazas.descripcion);
setCategorias(userChazas.categorias);
setFechaFundacion(userChazas.fechaFundacion);
setUbicacion(userChazas.ubicacion);
setHorarioAtencion(userChazas.horarioAtencion);*/
- }, [chazasFetch]);
+ }, []);
+ if (user.chaza && chazas.length == 0) {
+ //return
;
+ }
return (
-
- {user.chaza ? (
-
- {chazas.length == 0 ? (
-
+
+ {isLoading ? (
+
+ ) : (
+ <>
+ {isOpenDelete && (
+
{
+ router.push("/unbiters/profile", { scroll: false });
+ setIsOpenDelete(false);
+ }}
+ onRedirect={() => {
+ deleteCuenta();
+ //router.push("/unbiters/login", { scroll: false });
+ setIsOpenDelete(false);
+ }}
+ />
+ )}
+ {isOpenDesactivar && (
+ {
+ router.push("/unbiters/profile", { scroll: false });
+ setIsOpenDesactivar(false);
+ }}
+ onRedirect={() => {
+ desactivar();
+ //router.push("/unbiters/login", { scroll: false });
+ setIsOpenDesactivar(false);
+ }}
+ />
+ )}
+ {
+ userData.nivelSuscripcion == 0 && userData.chaza ?
+ : null
+ }
+ {user.chaza ? (
+ <>
+ {chazas.length == 0 ? (
+
+ ) : (
+ <>
+
+
+ {"Crear Chaza"}
+
+ {/*
+ setIsOpenDelete(true)}
+ type="button"
+ className="bg-[#d63447] inline-flex items-center px-5 py-2.5 mt-4 sm:mt-6 text-sm font-medium text-center text-white rounded-lg text-white focus:ring-4 focus:outline-none focus:ring-blue-300 dark:focus:ring-blue-800 shadow-lg shadow-blue-500/50 dark:shadow-lg dark:shadow-blue-800/80 font-medium rounded-lg text-sm px-5 py-2.5 text-center mr-2 mb-2 "
+ >
+ {"Eliminar Cuenta"}
+ */}
+ {userData.nivelSuscripcion == 1 ?
+ setIsOpenDesactivar(true)}
+ type="button"
+ className="bg-[#d63447] inline-flex items-center px-5 py-2.5 mt-4 sm:mt-6 text-sm font-medium text-center text-white rounded-lg text-white focus:ring-4 focus:outline-none focus:ring-blue-300 dark:focus:ring-blue-800 shadow-lg shadow-blue-500/50 dark:shadow-lg dark:shadow-blue-800/80 font-medium rounded-lg text-sm px-5 py-2.5 text-center mr-2 mb-2 "
+ >
+ {"Desactivar suscripción"}
+ : null
+
+ }
+
+
+ {chazas.map((chaza) => (
+
+ ))}
+
+ >
+ )}
+ >
) : (
-
-
-
- {"Crear Chaza"}
-
-
- {chazas.map((chaza) => (
-
-
-
- ))}
-
+
)}
-
- ) : (
-
+ >
)}
);
diff --git a/components/Cards/CardReview.js b/components/Cards/CardReview.js
index 502ab23..11520f4 100644
--- a/components/Cards/CardReview.js
+++ b/components/Cards/CardReview.js
@@ -17,7 +17,7 @@ export default function CardReview({
className,
card,
mode,
- idModal,
+ token,
idSearch,
deletePostUp,
editPostUp,
@@ -42,12 +42,13 @@ export default function CardReview({
const [isOpenDelete, setIsOpenDelete] = useState(false);
const [fill, setFill] = useState("");
const [fillText, setFillText] = useState("");
- const [token, setToken] = useState("");
+ //const [token, setToken] = useState("");
const [likes, setLikes] = useState(card.likes);
const [numComments, setNumComments] = useState(0);
var src = "/images/1499696010180-025ef6e1a8f9.jpg";
- if (card.imagenUrl) {
- src = card.imagenUrl;
+ if (card.imagenId) {
+ var url = card.imagenUrl.split("upload/")
+ src = url[0] + "upload/c_scale,h_300,w_500/" + url[1];
}
//console.log("card", card)
function openModal(token) {
@@ -128,13 +129,13 @@ export default function CardReview({
useEffect(() => {
//console.log(card.numComentarios)
setNumComments(card.numComentarios);
- var tkn = window.sessionStorage.getItem("token");
- setToken(tkn);
- if (tkn) {
+ //var tkn = window.sessionStorage.getItem("token");
+ //setToken(tkn);
+ if (token) {
client
.get("publications/" + card.id + "/likes/myLikeInPublication", {
headers: {
- Authorization: `Bearer ${tkn}`,
+ Authorization: `Bearer ${token}`,
},
})
.then((res) => {
@@ -148,10 +149,11 @@ export default function CardReview({
}, []);
return (
-
+
-
+
{card.texto}
{card.tags
? card.tags.map((categorias, id) => (
-
- #{categorias}
-
- ))
+
+ #{categorias}
+
+ ))
: null}
diff --git a/components/Cards/MyComments.js b/components/Cards/MyComments.js
index f5a6c27..18565fc 100644
--- a/components/Cards/MyComments.js
+++ b/components/Cards/MyComments.js
@@ -66,7 +66,7 @@ export default function MyComments({ comment, deleteCommentUp, editCommentUp })
*/}
-
{moment(comment.createdAt, "YYYYMMDD").format('LL')}
+
{moment(comment.createdAt, "YYYYMMDD").format('LL')}
diff --git a/components/Container.js b/components/Container.js
index 0985309..2a9ea2d 100644
--- a/components/Container.js
+++ b/components/Container.js
@@ -30,7 +30,7 @@ export default function Container({ setPosts, setCategorias, title, message, mod
*/}
-
404
+
{title ? title : "Filtro no encontrado"}
@@ -40,20 +40,30 @@ export default function Container({ setPosts, setCategorias, title, message, mod
: "Lo sentimos, no hay publicaciones relacionadas con el filtro escogido, prueba borrando los filtros."}
- {mode != "profile" ? (
-
- Quitar Filtros
-
+ {mode == "profile" ? (
+ Ver Publicaciones
+
) : (
-
- Ver Publicaciones
-
+ <>
+ {mode == "premium" ? (
+
+ Ver Planes
+ ) :
+ (
+
+ Quitar Filtros
+ )
+
+ }>
)}
diff --git a/components/Filter.js b/components/Filter.js
index 398a9b1..45139b8 100644
--- a/components/Filter.js
+++ b/components/Filter.js
@@ -1,112 +1,127 @@
-
-'use client'
+"use client";
import client from "@/config/client";
-import { Listbox, Transition, Switch } from '@headlessui/react'
-import { CheckIcon, ChevronUpDownIcon } from '@heroicons/react/20/solid'
+import { Listbox, Transition, Switch } from "@headlessui/react";
+import { CheckIcon, ChevronUpDownIcon } from "@heroicons/react/20/solid";
import { useEffect, useState, Fragment } from "react";
-export default function Filter({ className, categorias, setCategorias, posts, setPosts }) {
- const [search, setSearch] = useState("")
+export default function Filter({
+ className,
+ categorias,
+ setCategorias,
+ posts,
+ setPosts,
+ setSearch,
+ search,
+}) {
+ //const [search, setSearch] = useState("")
var categoriasLists = [
{
- "id": 1,
- "nombreCategoria": "Platos principales"
+ id: 1,
+ nombreCategoria: "Platos principales",
},
{
- "id": 2,
- "nombreCategoria": "Entrantes"
+ id: 2,
+ nombreCategoria: "Entrantes",
},
{
- "id": 3,
- "nombreCategoria": "Postres"
+ id: 3,
+ nombreCategoria: "Postres",
},
{
- "id": 4,
- "nombreCategoria": "Bebidas"
+ id: 4,
+ nombreCategoria: "Bebidas",
},
{
- "id": 5,
- "nombreCategoria": "Comidas rápidas"
+ id: 5,
+ nombreCategoria: "Comidas rápidas",
},
{
- "id": 6,
- "nombreCategoria": "Comidas vegetarianas"
+ id: 6,
+ nombreCategoria: "Comidas vegetarianas",
},
{
- "id": 7,
- "nombreCategoria": "Comidas veganas"
+ id: 7,
+ nombreCategoria: "Comidas veganas",
},
{
- "id": 8,
- "nombreCategoria": "Comidas saludables"
+ id: 8,
+ nombreCategoria: "Comidas saludables",
},
{
- "id": 9,
- "nombreCategoria": "Comidas internacionales"
+ id: 9,
+ nombreCategoria: "Comidas internacionales",
},
{
- "id": 10,
- "nombreCategoria": "Comidas tradicionales"
- }
- ]
+ id: 10,
+ nombreCategoria: "Comidas tradicionales",
+ },
+ ];
async function filterPost() {
try {
if (categorias.length != 0) {
-
- client.get(`publications`, { next: { revalidate: true | 0 | 60 } }).
- then((res) => {
-
+ client
+ .get(`publications`, { next: { revalidate: true | 0 | 60 } })
+ .then((res) => {
if (!res.status == "200") {
- throw new Error('Failed to fetch data')
+ throw new Error("Failed to fetch data");
}
- console.log("filterrr", categorias)
- var filterPost = posts.filter(item => {
+ console.log("filterrr", categorias);
+ var filterPost = posts.filter((item) => {
if (item.tags.length != 0) {
//console.log(item.tags)
- if (item.tags.includes(categorias[0], categorias[1], categorias[2])) {
- return item
+ if (
+ item.tags.includes(
+ categorias[0],
+ categorias[1],
+ categorias[2]
+ )
+ ) {
+ return item;
}
}
- })
- setPosts(filterPost)
+ });
+ setPosts(filterPost);
//if (!posts) return "An error has occurred.";
- })
+ });
}
} catch (error) {
- console.log(error)
+ console.log(error);
}
}
async function filterPostOff() {
try {
- client.get(`publications`, { next: { revalidate: true | 0 | 60 } }).
- then((res) => {
-
+ client
+ .get(`publications`, { next: { revalidate: true | 0 | 60 } })
+ .then((res) => {
if (!res.status == "200") {
- throw new Error('Failed to fetch data')
+ throw new Error("Failed to fetch data");
}
- setPosts(res.data.data.data)
- setCategorias([])
+ setPosts(res.data.data.data);
+ setCategorias([]);
//if (!posts) return "An error has occurred.";
- })
+ });
} catch (error) {
- console.log(error)
+ console.log(error);
}
}
async function searchButton() {
- console.log(search)
+ console.log(search);
try {
- client.post(`publications/searchPublication`, { filter: search }).
- then((res) => {
-
- if (!res.status == "200") {
- throw new Error('Failed to fetch data')
- }
- setPosts(res.data.data.data.hits)
- })
+ if (search != "") {
+ client
+ .post(`publications/searchPublication`, { filter: search })
+ .then((res) => {
+ if (!res.status == "200") {
+ throw new Error("Failed to fetch data");
+ }
+ //console.log(res.data.data.data.hits)
+ setPosts(res.data.data.data.hits);
+ });
+ }
} catch (error) {
- console.log(error)
+ console.log(error);
}
}
useEffect(() => {
@@ -122,19 +137,19 @@ export default function Filter({ className, categorias, setCategorias, posts, se
console.log(filterPost)
setPosts(filterPost)
}*/
- }, [])
+ }, []);
function MyMultiSelectCategorias() {
-
return (
-
+
-
-
-
- {"Filtra por categorias "}
+
+
+ {"Filtra por categorias "}
+
- {categorias.map((cate) => cate).join(', ')}
+ {categorias.map((cate) => cate).join(", ")}
+
-
{categoriasLists.map((cate) => (
- `relative cursor-default select-none py-2 pl-10 pr-4 ${active ? 'bg-amber-100 text-amber-900' : 'text-gray-900'
+ `relative cursor-default select-none py-2 pl-10 pr-4 ${
+ active
+ ? "bg-amber-100 text-amber-900"
+ : "text-gray-900"
}`
}
>
{({ categorias }) => (
<>
{cate.nombreCategoria}
{categorias ? (
-
+
) : null}
>
@@ -180,39 +204,72 @@ export default function Filter({ className, categorias, setCategorias, posts, se
- )
+ );
}
return (
-