Skip to content

Commit

Permalink
cambios
Browse files Browse the repository at this point in the history
  • Loading branch information
RyuDSora committed Aug 23, 2024
1 parent 50aff31 commit 582796b
Show file tree
Hide file tree
Showing 7 changed files with 266 additions and 16 deletions.
23 changes: 20 additions & 3 deletions client/src/components/Articles.jsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { useEffect, useState } from 'react';
import { Row, Col, Card, Modal, Button } from 'react-bootstrap';
import { url } from './Urls';
import { url,uritutor } from './Urls';
import axios from 'axios';
import Cookies from 'js-cookie';
import { decryptValue, encryptionKey } from './hashes';
import { toast, ToastContainer } from 'react-toastify';


const Articles = () => {
const [articles, setArticles] = useState([]);
Expand All @@ -18,8 +20,21 @@ const Articles = () => {
const session = Cookies.get('$3s1.4') ? decryptValue(Cookies.get('$3s1.4'), encryptionKey) : null;
if (session) {
const id = decryptValue(Cookies.get('#gt156'), encryptionKey); // Obtiene el ID del profesor
const leerTutor = async(ID) =>{
try {
const response = await axios.get(`${uritutor}/${ID}`);
const idTutor = response.data.id;
setTeacherId(idTutor)
} catch (error) {

}
}

const role = decryptValue(Cookies.get('&0l3'), encryptionKey); // Obtiene el rol del usuario
setTeacherId(id);
if (userRole === 'tutor') {
leerTutor(id)
}

setUserRole(role); // Establece el rol del usuario
setIsLoggedIn(true); // Si hay sesión, marcamos que el usuario está logueado
}
Expand All @@ -30,6 +45,7 @@ const Articles = () => {
const fetchArticles = async () => {
try {
let response;

if (userRole === 'tutor' && teacherId) {
// Obtener todos los artículos del tutor
response = await axios.get(`${url}/articles/teacher/${teacherId}`);
Expand All @@ -43,7 +59,7 @@ const Articles = () => {

// Si el usuario es tutor, ordenamos por comentarios de mayor a menor
if (userRole === 'tutor') {
articlesData.sort((a, b) => b.comments.length - a.comments.length); // Suponiendo que 'comments' es un array en cada artículo
//articlesData.sort((a, b) => b.comments.length - a.comments.length); // Suponiendo que 'comments' es un array en cada artículo
}

setArticles(articlesData);
Expand All @@ -69,6 +85,7 @@ const Articles = () => {

return (
<>
<ToastContainer/>
{isLoggedIn ? (
<>
<Row style={{ width: '100%' }}>
Expand Down
12 changes: 10 additions & 2 deletions client/src/components/DashboardStudent/ArticlesST.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Cookies from 'js-cookie';
import { decryptValue, encryptionKey } from '../hashes';
import { url } from '../Urls';
import axios from 'axios';
import { toast, ToastContainer } from 'react-toastify';

const ArticlesST = () => {
const [articles, setArticles] = useState([]);
Expand Down Expand Up @@ -73,11 +74,17 @@ const ArticlesST = () => {
});

// Actualiza artículos para incluir el nuevo comentario
setSelectedArticle(prev => ({
...prev,
comments: [...(prev.comments || []), response.data]
}) );

setArticles(prevArticles =>
prevArticles.map(article =>
article.id === articleId ? { ...article, comments: [...(article.comments || []), response.data] } : article
)
);
toast.success('se agregó su comentario')
setNewComment(""); // Resetea el comentario
} catch (error) {
console.error('Error adding comment:', error);
Expand All @@ -87,7 +94,8 @@ const ArticlesST = () => {

return (
<Container>
<h1>Libros</h1>
<ToastContainer/>
<div className='mb-3'><span className='h3 Principal f_principal'>Tus Artículos</span></div>
{loading ? (
<Spinner animation="border" />
) : error ? (
Expand Down Expand Up @@ -145,7 +153,7 @@ const ArticlesST = () => {
required
/>
</Form.Group>
<Button variant="primary" type="submit" className="mt-2">Enviar</Button>
<Button variant="primary" type="submit" className="mt-2 bg_secundario">Enviar</Button>
</Form>
) : (
<p>Debes estar autenticado para agregar comentarios.</p>
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/DashboardStudent/DashST.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

import TopSellingCourses from '../TopSellingCourses';
import TopSellingCourses from '../TopSellingCoursesST';
import Articles from "../Articles";
import NextLessons from '../NextLessonsST';

Expand Down
48 changes: 41 additions & 7 deletions client/src/components/DashboardTutor/ArticlesTU.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@ import { useEffect, useState, useCallback } from 'react';
import { Row, Col, Card, Modal, Button, Form } from 'react-bootstrap';
import axios from 'axios';
import Cookies from 'js-cookie';
import { confirmAlert } from 'react-confirm-alert';
import { decryptValue, encryptionKey } from '../hashes';
import { url } from '../Urls'; // Asegúrate de que la URL está configurada correctamente
import { url, uritutor } from '../Urls'; // Asegúrate de que la URL está configurada correctamente
import { toast, ToastContainer } from 'react-toastify';
import { FaTrash, FaEdit } from 'react-icons/fa';

const ArticlesTU = () => {
const [articles, setArticles] = useState([]);
Expand All @@ -21,8 +24,18 @@ const ArticlesTU = () => {
if (session) {
const role = decryptValue(Cookies.get('&0l3'), encryptionKey);
const id = decryptValue(Cookies.get('#gt156'), encryptionKey); // Esto obtiene el ID del usuario
const leerTutor = async(ID) =>{
try {
const response = await axios.get(`${uritutor}/${ID}`);
const idTutor = response.data.id;
setTeacherId(idTutor)
} catch (error) {

}
}
leerTutor(id);

setUserRole(role);
setTeacherId(id);
}
}, []);

Expand Down Expand Up @@ -66,31 +79,52 @@ const ArticlesTU = () => {
try {
if (isEditing) {
await axios.put(`${url}/articles/${selectedArticle.id}`, { ...formData });
toast.success('Se ha modificado el artículo exitosamente')
} else {
await axios.post(`${url}/articles`, { ...formData, teacher_id: teacherId });
toast.success('Se ha creado el artículo exitosamente')
}
fetchArticles();
handleCloseModal();
} catch (error) {
console.error('Error saving article:', error);
toast.error('No se puede crear el artículo')
}
};

const handleDelete = async (id) => {
try {
await axios.delete(`${url}/articles/${id}`);
toast.warning('Se eliminó el artículo exitosamente')
fetchArticles();
} catch (error) {
console.error('Error deleting article:', error);
}
};

const confirmDelete = (id) => {
confirmAlert({
title: 'Confirmar eliminación',
message: '¿Estás seguro de que deseas eliminar el Artículo?',
buttons: [
{
label: 'Sí',
onClick: () => { handleDelete(id) },
},
{
label: 'No',
onClick: () => { },
},
],
});
};
return (
<>
<ToastContainer/>
<div><span className='h3 Principal f_principal'>Tus Artículos</span></div>
{userRole && ( // Comprobación del rol de usuario
<div>
<h2>Gestión de Artículos</h2>
<Button variant="primary" onClick={() => { setShowModal(true); setIsEditing(false); setFormData({ title: '', content: '' }); }}>
<h2 className='Principal my-2'>Gestión de Artículos</h2>
<Button variant="primary" className='bg_secundario' onClick={() => { setShowModal(true); setIsEditing(false); setFormData({ title: '', content: '' }); }}>
Crear Artículo
</Button>

Expand All @@ -101,8 +135,8 @@ const ArticlesTU = () => {
<Card.Body>
<Card.Title className='small'>{article.title}</Card.Title>
<Card.Subtitle className="mb-2 text-muted">{new Date(article.created_at).toLocaleDateString()}</Card.Subtitle>
<Button variant="secondary" onClick={() => handleCardClick(article)} style={{ marginRight: '5px' }}>Editar</Button>
<Button variant="danger" onClick={() => handleDelete(article.id)}>Eliminar</Button>
<Button className='bg_principal' title='Editar' variant="secondary" onClick={() => handleCardClick(article)} style={{ marginRight: '5px' }}><FaEdit/></Button>
<Button variant="danger" title='Borrar' style={{backgroundColor:'red'}} onClick={() => confirmDelete(article.id)}><FaTrash/></Button>
</Card.Body>
</Card>
</Col>
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/NavBarT.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ function NavBarT({ isLoggedIn }) {
</>):(
<>{Tutor ? (<>
{/**aqui van las opciones del tutor */}
{lista("/dashboardtutor/dash",<FaHome />,'Mi Panel')}
{lista("/dashboardtutor/dash-tu",<FaHome />,'Mi Panel')}
{lista("/dashboardtutor/my-courses",<FaBook />,'Mis Cursos')}
{lista("/dashboardtutor/my-students",<FaUsers />,'Mis Estudiantes')}
{lista("/dashboardtutor/chats",<FaComments />,'Chats')}
Expand Down
Loading

0 comments on commit 582796b

Please sign in to comment.