Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

trabajo final frontend José Velásquez #16

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions app/bulkcreate/page.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
"use client"
import React, { useState } from 'react';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import Navbar from '@/components/Navbar';
import AuthService from '@/services/AuthService';
import { Snackbar, Alert } from '@mui/material';

const BulkAddUsers = () => {
const [users, setUsers] = useState([
{ name: '', email: '', cellphone: '', password: '' },
]);
const [snackbarOpen, setSnackbarOpen] = useState(false);
const [message, setMessage] = useState('');

const handleUserChange = (index, event) => {
const newUsers = [...users];
newUsers[index][event.target.name] = event.target.value;
setUsers(newUsers);
};

const addUser = () => {
setUsers([...users, { name: '', email: '', cellphone: '', password: '' }]);
};

const removeUser = (index) => {
const newUsers = [...users];
newUsers.splice(index, 1);
setUsers(newUsers);
};

const handleSubmit = async (e) => {
e.preventDefault();
try {
const payload = {
usersList: users
};
const token = localStorage.getItem('token');
const response = await AuthService.bulkCreate(payload, token);

if(response){
console.log(response.data);
setMessage(response.data);
setSnackbarOpen(true)
}

}
catch(e){
console.error(e);
setMessage("hubo un error");
setSnackbarOpen(true)
};
};

const handleCloseSnackbar = (event, reason) => {
if (reason === 'clickaway') {
return;
}
setSnackbarOpen(false);
};

return (
<form onSubmit={handleSubmit}>
<Navbar />
<Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginTop: '20px' }}>
<Snackbar message={message} open={snackbarOpen} autoHideDuration={6000} onClose={handleCloseSnackbar}/>
{users.map((user, index) => (
<Box key={index} sx={{ display: 'flex', alignItems: 'center', gap: 2, marginBottom: 2 }}>
<TextField
name="name"
label="Name"
value={user.name}
onChange={(e) => handleUserChange(index, e)}
/>
<TextField
name="email"
label="Email"
value={user.email}
onChange={(e) => handleUserChange(index, e)}
/>
<TextField
name="cellphone"
label="cellphone"
value={user.cellphone}
onChange={(e) => handleUserChange(index, e)}
/>
<TextField
name="password"
label="Password"
type="password"
value={user.password}
onChange={(e) => handleUserChange(index, e)}
/>
{index === users.length - 1 && (
<Button onClick={addUser} variant="contained" color="primary">
Add User
</Button>
)}
{users.length > 1 && (
<Button onClick={() => removeUser(index)} variant="contained" color="secondary">
Remove
</Button>
)}
</Box>
))}
<Button type="submit" variant="contained">Submit</Button>
</Box>
</form>
);
};

export default BulkAddUsers;
92 changes: 92 additions & 0 deletions app/findUsers/page.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
"use client"
import React, { useState, useEffect } from 'react';
import { TextField, Button, Stack, Container, Switch, Table, TableBody, TableCell, TableHead, TableRow } from '@mui/material';
import Navbar from '@/components/Navbar';
import AuthService from "../../services/AuthService";
import { useRouter } from 'next/navigation';

const UserFilters = ({ onFilter }) => {
const router = useRouter();

const [query, setQuery] = useState({ name : '', loginBeforeDate: '', loginAfterDate: '', status : true });

const handleInputChange = (e) => {
const { name, value } = e.target;
setQuery((prevQuery) => ({
...prevQuery,
[name]: value,
}));
}

const [users, setUsers] = useState([]);
useEffect(() => {
const user = JSON.parse(localStorage.getItem('user'));
if(!user){
router.push('/login');
}

getUser();

}, []);

const getUser = async (query) => {
const token = localStorage.getItem('token');
const data = await AuthService.getfindUsers(query, token);
setUsers(data);
console.log(data);
}

const handleSubmit = (event) => {
event.preventDefault();
getUser(query);
console.log(users);
};
console.log(query);
return (
<form onSubmit={handleSubmit}>
<Navbar />
<Container sx={{ marginTop: 10 }}>
<Stack spacing={5} sx={{ justifyContent: 'center' }}>
<Stack direction="row" spacing={5} sx={{ justifyContent: 'center' }}>
<TextField name="name" label="Name" value={query.name} onChange={handleInputChange} />
<TextField name="createdBefore" type="date" value={query.createdBefore} onChange={handleInputChange} />
<TextField name="createdAfter" type="date" value={query.createdAfter} onChange={handleInputChange} />
<Switch
checked={query.status}
onChange={(e) => {
const updatedQuery = { ...query, status: e.target.checked };
setQuery(updatedQuery);
}}
inputProps={{ 'aria-label': 'Status' }}
/>
<Button type="submit" onClick={handleSubmit}>Filter</Button>
</Stack>
<Table>
<TableHead>
<TableRow>
<TableCell>Nombre</TableCell>
<TableCell>Email</TableCell>
<TableCell>Estado</TableCell>
<TableCell>Última Sesión</TableCell>
</TableRow>
</TableHead>
<TableBody>
{
users.map((user) => (
<TableRow key={user}>
<TableCell>{user.name}</TableCell>
<TableCell>{user.email}</TableCell>
<TableCell>{user.status ? 'ACTIVO' : 'CERRADO'}</TableCell>
<TableCell>{new Date(user.updatedAt).toLocaleDateString('es-ES')}</TableCell>
</TableRow>
))
}
</TableBody>
</Table>
</Stack>
</Container>
</form>
);
};

export default UserFilters;
9 changes: 7 additions & 2 deletions components/Navbar.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import './Navbar.css';
import Button from '@mui/material/Button';
import AuthService from '@/services/AuthService';
import { useRouter } from 'next/navigation';
import Stack from '@mui/material/Stack';

const Navbar = () => {
const router = useRouter();
Expand All @@ -22,9 +23,13 @@ const Navbar = () => {

return (
<div className="navbar">
<div className="navbar-item">
<Stack direction="row" spacing={5} className="navbar-item">
{user?.name}
</div>
<Button onClick={() => router.push('/users')}>Home</Button>
<Button onClick={() => router.push('/findUsers')}>Buscar</Button>
<Button onClick={() => router.push('/bulkCreate')}>Ingresar usuarios</Button>

</Stack>
<div className="navbar-item">
<Button onClick={handleLogout}>
Logout
Expand Down
35 changes: 35 additions & 0 deletions services/AuthService.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,22 @@ const getUserById = async (id, token) => {
}
}

const getfindUsers = async (query, token) => {
const queryparams = new URLSearchParams(query).toString();
try {
console.log("nquery",query);
const response = await axios.get('http://localhost:3001/api/v1/users/findUsers?' + queryparams, {
headers: {
token,
}
});
return response.data;
} catch(e){
console.error(e);
return null;
}
}

const logOut = async (token) => {
try {
const response = await axios.post('http://localhost:3001/api/v1/auth/logout', {}, {
Expand Down Expand Up @@ -100,6 +116,23 @@ const registerUser = async (name, email, password, password_second, cellphone) =
}
}

const bulkCreate = async (body, token) => {
console.log("Esta intentando enviar", body);
try {
console.log("Esta intentando enviar", body);
const response = await axios.post('http://localhost:3001/api/v1/users/bulkCreate', body, {
headers: {
'token': token,
}
});
console.log(response);
return (response);
} catch (e) {
console.error(e);
return false;
}
}

const updateUser = async (id, user, token) => {
try {
const response = await axios.put('http://localhost:3001/api/v1/users/' + id, user, {
Expand All @@ -121,4 +154,6 @@ export default {
logOut,
registerUser,
updateUser,
getfindUsers,
bulkCreate,
};