[REPO REFACTOR]: changed to a better git repository structure with branches
This commit is contained in:
92
src/components/AnimatedDropdown.jsx
Normal file
92
src/components/AnimatedDropdown.jsx
Normal file
@@ -0,0 +1,92 @@
|
||||
import { useState, useRef, useEffect, cloneElement } from 'react';
|
||||
import { Button } from 'react-bootstrap';
|
||||
import { AnimatePresence, motion as _motion } from 'framer-motion';
|
||||
import '../css/AnimatedDropdown.css';
|
||||
|
||||
const AnimatedDropdown = ({
|
||||
trigger,
|
||||
icon,
|
||||
variant = "secondary",
|
||||
className = "",
|
||||
buttonStyle = "",
|
||||
show,
|
||||
onToggle,
|
||||
onMouseEnter,
|
||||
onMouseLeave,
|
||||
children
|
||||
}) => {
|
||||
const isControlled = show !== undefined;
|
||||
const [open, setOpen] = useState(false);
|
||||
const triggerRef = useRef(null);
|
||||
const dropdownRef = useRef(null);
|
||||
|
||||
const actualOpen = isControlled ? show : open;
|
||||
|
||||
const toggle = () => {
|
||||
const newState = !actualOpen;
|
||||
if (!isControlled) setOpen(newState);
|
||||
onToggle?.(newState);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (e) => {
|
||||
if (
|
||||
dropdownRef.current &&
|
||||
!dropdownRef.current.contains(e.target) &&
|
||||
!triggerRef.current?.contains(e.target)
|
||||
) {
|
||||
if (!isControlled) setOpen(false);
|
||||
onToggle?.(false);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener("mousedown", handleClickOutside);
|
||||
return () => document.removeEventListener("mousedown", handleClickOutside);
|
||||
}, [isControlled, onToggle]);
|
||||
|
||||
const triggerElement = trigger
|
||||
? (typeof trigger === "function"
|
||||
? trigger({ onClick: toggle, ref: triggerRef })
|
||||
: cloneElement(trigger, { onClick: toggle, ref: triggerRef }))
|
||||
: (
|
||||
<Button
|
||||
ref={triggerRef}
|
||||
variant={variant}
|
||||
className={`circle-btn ${buttonStyle}`}
|
||||
onClick={toggle}
|
||||
>
|
||||
{icon}
|
||||
</Button>
|
||||
);
|
||||
|
||||
const dropdownClasses = `dropdown-menu show shadow rounded-4 px-2 py-2 ${className}`;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`position-relative d-inline-block`}
|
||||
onClick={toggle}
|
||||
onMouseEnter={onMouseEnter}
|
||||
onMouseLeave={onMouseLeave}
|
||||
ref={triggerRef}
|
||||
>
|
||||
{triggerElement}
|
||||
|
||||
<AnimatePresence>
|
||||
{actualOpen && (
|
||||
<_motion.div
|
||||
ref={dropdownRef}
|
||||
initial={{ opacity: 0, scale: 0.98 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.98 }}
|
||||
transition={{ duration: 0.15 }}
|
||||
className={dropdownClasses}
|
||||
>
|
||||
{typeof children === "function" ? children({ closeDropdown: () => toggle(false) }) : children}
|
||||
</_motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AnimatedDropdown;
|
||||
122
src/components/AnimatedDropend.jsx
Normal file
122
src/components/AnimatedDropend.jsx
Normal file
@@ -0,0 +1,122 @@
|
||||
import { useState, useRef, useEffect, cloneElement } from 'react';
|
||||
import { Button } from 'react-bootstrap';
|
||||
import { AnimatePresence, motion as _motion } from 'framer-motion';
|
||||
import '../css/AnimatedDropdown.css';
|
||||
|
||||
const AnimatedDropend = ({
|
||||
trigger,
|
||||
icon,
|
||||
variant = "secondary",
|
||||
className = "",
|
||||
buttonStyle = "",
|
||||
show,
|
||||
onToggle,
|
||||
onMouseEnter,
|
||||
onMouseLeave,
|
||||
children
|
||||
}) => {
|
||||
const isControlled = show !== undefined;
|
||||
const [open, setOpen] = useState(false);
|
||||
const triggerRef = useRef(null);
|
||||
const dropdownRef = useRef(null);
|
||||
|
||||
const actualOpen = isControlled ? show : open;
|
||||
|
||||
const toggle = (forceValue) => {
|
||||
const newState = typeof forceValue === "boolean" ? forceValue : !actualOpen;
|
||||
if (!isControlled) setOpen(newState);
|
||||
onToggle?.(newState);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (e) => {
|
||||
if (
|
||||
dropdownRef.current &&
|
||||
!dropdownRef.current.contains(e.target) &&
|
||||
!triggerRef.current?.contains(e.target)
|
||||
) {
|
||||
if (!isControlled) setOpen(false);
|
||||
onToggle?.(false);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener("mousedown", handleClickOutside);
|
||||
return () => document.removeEventListener("mousedown", handleClickOutside);
|
||||
}, [isControlled, onToggle]);
|
||||
|
||||
const handleMouseEnter = () => {
|
||||
if (!isControlled) setOpen(true);
|
||||
onToggle?.(true);
|
||||
onMouseEnter?.();
|
||||
};
|
||||
|
||||
const handleMouseLeave = () => {
|
||||
if (!isControlled) setOpen(false);
|
||||
onToggle?.(false);
|
||||
onMouseLeave?.();
|
||||
};
|
||||
|
||||
const triggerElement = trigger
|
||||
? (typeof trigger === "function"
|
||||
? trigger({
|
||||
onClick: e => {
|
||||
e.stopPropagation();
|
||||
toggle();
|
||||
},
|
||||
ref: triggerRef
|
||||
})
|
||||
: cloneElement(trigger, {
|
||||
onClick: e => {
|
||||
e.stopPropagation();
|
||||
toggle();
|
||||
},
|
||||
ref: triggerRef
|
||||
}))
|
||||
: (
|
||||
<Button
|
||||
ref={triggerRef}
|
||||
variant={variant}
|
||||
className={`circle-btn ${buttonStyle}`}
|
||||
onClick={toggle}
|
||||
>
|
||||
{icon}
|
||||
</Button>
|
||||
);
|
||||
|
||||
const dropdownClasses = `dropdown-menu show shadow rounded-4 px-2 py-2 ${className}`;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="position-relative d-inline-block dropend"
|
||||
onMouseEnter={handleMouseEnter}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
ref={triggerRef}
|
||||
>
|
||||
{triggerElement}
|
||||
|
||||
<AnimatePresence>
|
||||
{actualOpen && (
|
||||
<_motion.div
|
||||
ref={dropdownRef}
|
||||
initial={{ opacity: 0, x: -10 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0, x: -10 }}
|
||||
transition={{ duration: 0.15 }}
|
||||
className={dropdownClasses}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: '0',
|
||||
left: '100%',
|
||||
zIndex: 1000,
|
||||
whiteSpace: 'nowrap'
|
||||
}}
|
||||
>
|
||||
{typeof children === "function" ? children({ closeDropdown: () => toggle(false) }) : children}
|
||||
</_motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AnimatedDropend;
|
||||
210
src/components/Anuncios/AnuncioCard.jsx
Normal file
210
src/components/Anuncios/AnuncioCard.jsx
Normal file
@@ -0,0 +1,210 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Card, Button, Form } from 'react-bootstrap';
|
||||
import AnimatedDropdown from '../../components/AnimatedDropdown';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { faEdit, faTrash, faEllipsisVertical } from '@fortawesome/free-solid-svg-icons';
|
||||
import '../../css/AnuncioCard.css';
|
||||
import { renderErrorAlert } from '../../util/alertHelpers';
|
||||
import {
|
||||
EditorProvider,
|
||||
Editor,
|
||||
} from 'react-simple-wysiwyg';
|
||||
import {
|
||||
Toolbar,
|
||||
Separator,
|
||||
BtnBold,
|
||||
BtnItalic,
|
||||
BtnUnderline,
|
||||
BtnStrikeThrough,
|
||||
BtnNumberedList,
|
||||
BtnBulletList,
|
||||
BtnLink,
|
||||
BtnClearFormatting,
|
||||
} from 'react-simple-wysiwyg';
|
||||
import DOMPurify from 'dompurify';
|
||||
|
||||
const PRIORITY_CONFIG = {
|
||||
0: { label: 'BAJA', className: 'text-success' },
|
||||
1: { label: 'MEDIA', className: 'text-warning' },
|
||||
2: { label: 'ALTA', className: 'text-danger' },
|
||||
};
|
||||
|
||||
const formatDateTime = (iso) => {
|
||||
const date = new Date(iso);
|
||||
return {
|
||||
date: date.toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit', year: 'numeric' }),
|
||||
time: date.toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit', hour12: false }),
|
||||
};
|
||||
};
|
||||
|
||||
const AnuncioCard = ({ anuncio, isNew = false, onCreate, onUpdate, onDelete, onCancel, error, onClearError }) => {
|
||||
const createMode = isNew;
|
||||
const [editMode, setEditMode] = useState(createMode);
|
||||
const [showFullBody, setShowFullBody] = useState(false);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
body: anuncio.body || '',
|
||||
priority: anuncio.priority ?? 1,
|
||||
published_by: JSON.parse(localStorage.getItem('user'))?.user_id,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!editMode) {
|
||||
setFormData({
|
||||
body: anuncio.body || '',
|
||||
priority: anuncio.priority ?? 1,
|
||||
published_by: JSON.parse(localStorage.getItem('user'))?.user_id,
|
||||
});
|
||||
}
|
||||
}, [anuncio, editMode]);
|
||||
|
||||
const handleEdit = () => {
|
||||
if (onClearError) onClearError();
|
||||
setEditMode(true);
|
||||
};
|
||||
|
||||
const handleDelete = () => typeof onDelete === 'function' && onDelete(anuncio.announce_id);
|
||||
|
||||
const handleCancel = () => {
|
||||
if (onClearError) onClearError();
|
||||
if (createMode && onCancel) return onCancel();
|
||||
setEditMode(false);
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
if (onClearError) onClearError();
|
||||
const sanitizedBody = DOMPurify.sanitize(formData.body);
|
||||
formData.body = sanitizedBody;
|
||||
const updated = { ...anuncio, ...formData };
|
||||
if (createMode && typeof onCreate === 'function') return onCreate(updated);
|
||||
if (typeof onUpdate === 'function') return onUpdate(updated, anuncio.announce_id);
|
||||
};
|
||||
|
||||
const handleChange = (field, value) => setFormData((prev) => ({ ...prev, [field]: value }));
|
||||
|
||||
const { date, time } = formatDateTime(anuncio.created_at);
|
||||
const priorityInfo = PRIORITY_CONFIG[formData.priority] || PRIORITY_CONFIG[1];
|
||||
const isLongBody = formData.body.length > 300;
|
||||
const displayBody = isLongBody && !showFullBody
|
||||
? `${formData.body.slice(0, 300)}...`
|
||||
: formData.body;
|
||||
|
||||
const insertImage = () => {
|
||||
const url = prompt('Introduce la URL de la imagen:');
|
||||
if (url) {
|
||||
const imgHTML = `<img src="${url}" alt="imagen" style="max-width: 100%;" />`;
|
||||
handleChange('body', formData.body + imgHTML);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="anuncio-card rounded-4 border-0 shadow-sm mb-4">
|
||||
<Card.Header className="d-flex justify-content-between align-items-center rounded-top-4 px-3 py-2">
|
||||
<div className="d-flex flex-column">
|
||||
<span className="fw-bold">📢 Anuncio #{anuncio.announce_id}</span>
|
||||
<small className="muted">
|
||||
Publicado el {date} a las {time} por{' '}
|
||||
<span className="fw-semibold">#{anuncio.published_by}</span>
|
||||
</small>
|
||||
</div>
|
||||
{!createMode && !editMode && (
|
||||
<AnimatedDropdown
|
||||
className="end-0"
|
||||
buttonStyle="bg-transparent border-0"
|
||||
icon={<FontAwesomeIcon icon={faEllipsisVertical} className="fa-xl" />}
|
||||
>
|
||||
{({ closeDropdown }) => (
|
||||
<>
|
||||
<div className="dropdown-item d-flex align-items-center" onClick={() => { handleEdit(); closeDropdown(); }}>
|
||||
<FontAwesomeIcon icon={faEdit} className="me-2" />Editar
|
||||
</div>
|
||||
<hr className="dropdown-divider" />
|
||||
<div className="dropdown-item d-flex align-items-center text-danger" onClick={() => { handleDelete(); closeDropdown(); }}>
|
||||
<FontAwesomeIcon icon={faTrash} className="me-2" />Eliminar
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</AnimatedDropdown>
|
||||
)}
|
||||
</Card.Header>
|
||||
|
||||
<Card.Body className="py-3">
|
||||
{(editMode || createMode) && renderErrorAlert(error)}
|
||||
|
||||
{editMode || createMode ? (
|
||||
<EditorProvider>
|
||||
<Editor
|
||||
value={formData.body}
|
||||
onChange={(e) => handleChange('body', e.target.value)}
|
||||
containerProps={{ className: 'mb-2' }}
|
||||
>
|
||||
<Toolbar>
|
||||
<BtnBold />
|
||||
<BtnItalic />
|
||||
<BtnUnderline />
|
||||
<BtnStrikeThrough />
|
||||
<BtnClearFormatting />
|
||||
<Separator />
|
||||
<BtnNumberedList />
|
||||
<BtnBulletList />
|
||||
<Separator />
|
||||
<BtnLink />
|
||||
<button
|
||||
type="button"
|
||||
onClick={insertImage}
|
||||
className="btn"
|
||||
title="Insertar imagen desde URL"
|
||||
>
|
||||
🖼️
|
||||
</button>
|
||||
</Toolbar>
|
||||
</Editor>
|
||||
</EditorProvider>
|
||||
) : (
|
||||
<>
|
||||
<div className="mb-2" dangerouslySetInnerHTML={{ __html: displayBody }} />
|
||||
|
||||
{isLongBody && (
|
||||
<Button variant='info'
|
||||
className="fw-medium text-dark mt-2"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
setShowFullBody((prev) => !prev);
|
||||
}}
|
||||
>
|
||||
{showFullBody ? 'Leer menos' : 'Leer más'}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{editMode && (
|
||||
<Form.Select
|
||||
className="mb-2 themed-input"
|
||||
value={formData.priority}
|
||||
onChange={(e) => handleChange('priority', parseInt(e.target.value))}
|
||||
>
|
||||
<option value={0}>Prioridad Baja</option>
|
||||
<option value={1}>Prioridad Media</option>
|
||||
<option value={2}>Prioridad Alta</option>
|
||||
</Form.Select>
|
||||
)}
|
||||
|
||||
{editMode && (
|
||||
<div className="d-flex justify-content-end gap-2">
|
||||
<Button variant="secondary" size="sm" onClick={handleCancel}>Cancelar</Button>
|
||||
<Button variant="primary" size="sm" onClick={handleSave}>Guardar</Button>
|
||||
</div>
|
||||
)}
|
||||
</Card.Body>
|
||||
|
||||
{!editMode && (
|
||||
<Card.Footer className="priority-footer text-center rounded-bottom-4 fw-medium py-2">
|
||||
Prioridad: <span className={`fw-bold ${priorityInfo.className}`}>{priorityInfo.label}</span>
|
||||
</Card.Footer>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
export default AnuncioCard;
|
||||
108
src/components/Anuncios/AnunciosFilter.jsx
Normal file
108
src/components/Anuncios/AnunciosFilter.jsx
Normal file
@@ -0,0 +1,108 @@
|
||||
import PropTypes from 'prop-types';
|
||||
|
||||
const AnunciosFilter = ({ filters, onChange }) => {
|
||||
const handleCheckboxChange = (key) => {
|
||||
const updated = { ...filters, [key]: !filters[key] };
|
||||
const allPrioridades = ['baja', 'media', 'alta'];
|
||||
const allFechas = ['ultimos7', 'esteMes'];
|
||||
|
||||
updated.todos = (
|
||||
allPrioridades.every(p => updated[p]) &&
|
||||
allFechas.every(f => updated[f])
|
||||
);
|
||||
onChange(updated);
|
||||
};
|
||||
|
||||
const handleTodosChange = () => {
|
||||
const newValue = !filters.todos;
|
||||
onChange({
|
||||
todos: newValue,
|
||||
baja: newValue,
|
||||
media: newValue,
|
||||
alta: newValue,
|
||||
ultimos7: newValue,
|
||||
esteMes: newValue
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="dropdown-item d-flex align-items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="todosCheck"
|
||||
className="me-2"
|
||||
checked={filters.todos}
|
||||
onChange={handleTodosChange}
|
||||
/>
|
||||
<label htmlFor="todosCheck" className="m-0">Mostrar Todos</label>
|
||||
</div>
|
||||
|
||||
<hr className="dropdown-divider" />
|
||||
|
||||
<div className="dropdown-item d-flex align-items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="bajaCheck"
|
||||
className="me-2"
|
||||
checked={filters.baja}
|
||||
onChange={() => handleCheckboxChange('baja')}
|
||||
/>
|
||||
<label htmlFor="bajaCheck" className="m-0">Prioridad Baja</label>
|
||||
</div>
|
||||
|
||||
<div className="dropdown-item d-flex align-items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="mediaCheck"
|
||||
className="me-2"
|
||||
checked={filters.media}
|
||||
onChange={() => handleCheckboxChange('media')}
|
||||
/>
|
||||
<label htmlFor="mediaCheck" className="m-0">Prioridad Media</label>
|
||||
</div>
|
||||
|
||||
<div className="dropdown-item d-flex align-items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="altaCheck"
|
||||
className="me-2"
|
||||
checked={filters.alta}
|
||||
onChange={() => handleCheckboxChange('alta')}
|
||||
/>
|
||||
<label htmlFor="altaCheck" className="m-0">Prioridad Alta</label>
|
||||
</div>
|
||||
|
||||
<hr className="dropdown-divider" />
|
||||
|
||||
<div className="dropdown-item d-flex align-items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="ultimos7Check"
|
||||
className="me-2"
|
||||
checked={filters.ultimos7}
|
||||
onChange={() => handleCheckboxChange('ultimos7')}
|
||||
/>
|
||||
<label htmlFor="ultimos7Check" className="m-0">Últimos 7 días</label>
|
||||
</div>
|
||||
|
||||
<div className="dropdown-item d-flex align-items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="esteMesCheck"
|
||||
className="me-2"
|
||||
checked={filters.esteMes}
|
||||
onChange={() => handleCheckboxChange('esteMes')}
|
||||
/>
|
||||
<label htmlFor="esteMesCheck" className="m-0">Este mes</label>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
AnunciosFilter.propTypes = {
|
||||
filters: PropTypes.object.isRequired,
|
||||
onChange: PropTypes.func.isRequired
|
||||
};
|
||||
|
||||
export default AnunciosFilter;
|
||||
89
src/components/App.jsx
Normal file
89
src/components/App.jsx
Normal file
@@ -0,0 +1,89 @@
|
||||
import Header from './Header'
|
||||
import NavBar from './NavBar/NavBar'
|
||||
import Footer from './Footer'
|
||||
import { Route, Routes, useLocation } from 'react-router-dom'
|
||||
import ProtectedRoute from './Auth/ProtectedRoute.jsx'
|
||||
import useSessionRenewal from '../hooks/useSessionRenewal'
|
||||
|
||||
import Home from '../pages/Home'
|
||||
import Socios from '../pages/Socios'
|
||||
import Ingresos from '../pages/Ingresos'
|
||||
import Gastos from '../pages/Gastos'
|
||||
import Balance from '../pages/Balance'
|
||||
import Login from '../pages/Login'
|
||||
import Solicitudes from '../pages/Solicitudes'
|
||||
import Anuncios from '../pages/Anuncios'
|
||||
import ListaEspera from '../pages/ListaEspera'
|
||||
import Building from '../pages/Building'
|
||||
import Documentacion from '../pages/Documentacion'
|
||||
|
||||
import { CONSTANTS } from '../util/constants'
|
||||
import Perfil from '../pages/Perfil.jsx'
|
||||
import Correo from '../pages/Correo.jsx'
|
||||
|
||||
function App() {
|
||||
const { modal: sessionModal } = useSessionRenewal();
|
||||
const routesWithFooter = ["/", "/lista-espera", "/login", "/gestion/socios", "/gestion/ingresos", "/gestion/gastos", "/gestion/balance"];
|
||||
|
||||
return (
|
||||
<>
|
||||
<Header />
|
||||
<NavBar />
|
||||
<Routes>
|
||||
<Route path="/" element={<Home />} />
|
||||
<Route path="/lista-espera" element={<ListaEspera />} />
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/gestion/socios" element={
|
||||
<ProtectedRoute minimumRoles={[CONSTANTS.ROLE_ADMIN, CONSTANTS.ROLE_DEV]}>
|
||||
<Socios />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
<Route path="/gestion/ingresos" element={
|
||||
<ProtectedRoute minimumRoles={[CONSTANTS.ROLE_ADMIN, CONSTANTS.ROLE_DEV]}>
|
||||
<Ingresos />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
<Route path="/gestion/gastos" element={
|
||||
<ProtectedRoute minimumRoles={[CONSTANTS.ROLE_ADMIN, CONSTANTS.ROLE_DEV]}>
|
||||
<Gastos />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
<Route path="/gestion/balance" element={
|
||||
<ProtectedRoute minimumRoles={[CONSTANTS.ROLE_ADMIN, CONSTANTS.ROLE_DEV]}>
|
||||
<Balance />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
<Route path="/documentacion" element={
|
||||
<ProtectedRoute>
|
||||
<Documentacion />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
<Route path="/anuncios" element={
|
||||
<ProtectedRoute>
|
||||
<Anuncios />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
<Route path="/gestion/solicitudes" element={
|
||||
<ProtectedRoute minimumRoles={[CONSTANTS.ROLE_ADMIN, CONSTANTS.ROLE_DEV]}>
|
||||
<Solicitudes />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
<Route path="/perfil" element={
|
||||
<ProtectedRoute>
|
||||
<Perfil />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
<Route path="/correo" element={
|
||||
<ProtectedRoute minimumRoles={[CONSTANTS.ROLE_ADMIN, CONSTANTS.ROLE_DEV]}>
|
||||
<Correo />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
<Route path="/*" element={<Building />} />
|
||||
</Routes>
|
||||
{routesWithFooter.includes(useLocation().pathname) ? <Footer /> : null}
|
||||
{sessionModal}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default App
|
||||
8
src/components/Auth/IfAuthenticated.jsx
Normal file
8
src/components/Auth/IfAuthenticated.jsx
Normal file
@@ -0,0 +1,8 @@
|
||||
import { useAuth } from "../../hooks/useAuth.js";
|
||||
|
||||
const IfAuthenticated = ({ children }) => {
|
||||
const { authStatus } = useAuth();
|
||||
return authStatus === "authenticated" ? children : null;
|
||||
};
|
||||
|
||||
export default IfAuthenticated;
|
||||
8
src/components/Auth/IfNotAuthenticated.jsx
Normal file
8
src/components/Auth/IfNotAuthenticated.jsx
Normal file
@@ -0,0 +1,8 @@
|
||||
import { useAuth } from "../../hooks/useAuth.js";
|
||||
|
||||
const IfNotAuthenticated = ({ children }) => {
|
||||
const { authStatus } = useAuth();
|
||||
return authStatus === "unauthenticated" ? children : null;
|
||||
};
|
||||
|
||||
export default IfNotAuthenticated;
|
||||
13
src/components/Auth/IfRole.jsx
Normal file
13
src/components/Auth/IfRole.jsx
Normal file
@@ -0,0 +1,13 @@
|
||||
import { useAuth } from "../../hooks/useAuth.js";
|
||||
|
||||
const IfRole = ({ roles, children }) => {
|
||||
const { user, authStatus } = useAuth();
|
||||
|
||||
if (authStatus !== "authenticated") return null;
|
||||
|
||||
const userRole = user?.role;
|
||||
|
||||
return roles.includes(userRole) ? children : null;
|
||||
};
|
||||
|
||||
export default IfRole;
|
||||
120
src/components/Auth/LoginForm.jsx
Normal file
120
src/components/Auth/LoginForm.jsx
Normal file
@@ -0,0 +1,120 @@
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { faUser } from '@fortawesome/free-solid-svg-icons';
|
||||
import { Form, Button, Alert, FloatingLabel, Row, Col } from 'react-bootstrap';
|
||||
import PasswordInput from './PasswordInput.jsx';
|
||||
|
||||
import { useContext, useState } from "react";
|
||||
import { Link, useNavigate } from "react-router-dom";
|
||||
import { AuthContext } from "../../context/AuthContext.jsx";
|
||||
|
||||
import CustomContainer from '../CustomContainer.jsx';
|
||||
import ContentWrapper from '../ContentWrapper.jsx';
|
||||
|
||||
import '../../css/LoginForm.css';
|
||||
|
||||
const LoginForm = () => {
|
||||
const { login, error } = useContext(AuthContext);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [formState, setFormState] = useState({
|
||||
emailOrUserName: "",
|
||||
password: "",
|
||||
keepLoggedIn: false
|
||||
});
|
||||
|
||||
const handleChange = (e) => {
|
||||
const { name, value } = e.target;
|
||||
setFormState((prev) => ({ ...prev, [name]: value }));
|
||||
};
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
const isEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formState.emailOrUserName);
|
||||
|
||||
const loginBody = {
|
||||
password: formState.password,
|
||||
keepLoggedIn: Boolean(formState.keepLoggedIn),
|
||||
};
|
||||
|
||||
if (isEmail) {
|
||||
loginBody.email = formState.emailOrUserName;
|
||||
} else {
|
||||
loginBody.userName = formState.emailOrUserName;
|
||||
}
|
||||
|
||||
try {
|
||||
await login(loginBody);
|
||||
navigate("/");
|
||||
} catch (err) {
|
||||
console.error("Error de login:", err.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<CustomContainer>
|
||||
<ContentWrapper>
|
||||
<div className="login-card card shadow p-5 rounded-5 mx-auto col-12 col-md-8 col-lg-6 col-xl-5 d-flex flex-column gap-4">
|
||||
<h1 className="text-center">Inicio de sesión</h1>
|
||||
<Form className="d-flex flex-column gap-5" onSubmit={handleSubmit}>
|
||||
<div className="d-flex flex-column gap-3">
|
||||
<FloatingLabel
|
||||
controlId="floatingUsuario"
|
||||
label={
|
||||
<>
|
||||
<FontAwesomeIcon icon={faUser} className="me-2" />
|
||||
Usuario o Email
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Form.Control
|
||||
type="text"
|
||||
placeholder=""
|
||||
name="emailOrUserName"
|
||||
value={formState.emailOrUserName}
|
||||
onChange={handleChange}
|
||||
className="rounded-4"
|
||||
/>
|
||||
</FloatingLabel>
|
||||
|
||||
<PasswordInput
|
||||
value={formState.password}
|
||||
onChange={handleChange}
|
||||
name="password"
|
||||
/>
|
||||
|
||||
<div className="d-flex flex-column flex-sm-row justify-content-between align-items-center gap-2">
|
||||
<Form.Check
|
||||
type="checkbox"
|
||||
name="keepLoggedIn"
|
||||
label="Mantener sesión iniciada"
|
||||
className="text-secondary"
|
||||
value={formState.keepLoggedIn}
|
||||
onChange={(e) => { formState.keepLoggedIn = e.target.checked; setFormState({ ...formState }) }}
|
||||
/>
|
||||
{/*<Link disabled to="#" className="muted">
|
||||
Olvidé mi contraseña
|
||||
</Link>*/}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<Alert variant="danger" className="text-center py-2 mb-0">
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="text-center">
|
||||
<Button type="submit" className="w-75 padding-4 rounded-4 border-0 shadow-sm login-button">
|
||||
Iniciar sesión
|
||||
</Button>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
</ContentWrapper>
|
||||
</CustomContainer>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
export default LoginForm;
|
||||
48
src/components/Auth/PasswordInput.jsx
Normal file
48
src/components/Auth/PasswordInput.jsx
Normal file
@@ -0,0 +1,48 @@
|
||||
import { useState } from 'react';
|
||||
import { Form, FloatingLabel, Button } from 'react-bootstrap';
|
||||
import '../../css/PasswordInput.css';
|
||||
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { faEye, faEyeSlash, faKey } from '@fortawesome/free-solid-svg-icons';
|
||||
|
||||
const PasswordInput = ({ value, onChange, name = "password" }) => {
|
||||
const [show, setShow] = useState(false);
|
||||
|
||||
const toggleShow = () => setShow(prev => !prev);
|
||||
|
||||
return (
|
||||
<div className="position-relative w-100">
|
||||
<FloatingLabel
|
||||
controlId="passwordInput"
|
||||
label={
|
||||
<>
|
||||
<FontAwesomeIcon icon={faKey} className="me-2" />
|
||||
Contraseña
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Form.Control
|
||||
type={show ? "text" : "password"}
|
||||
name={name}
|
||||
value={value}
|
||||
placeholder=""
|
||||
onChange={onChange}
|
||||
className="rounded-4 pe-5"
|
||||
/>
|
||||
</FloatingLabel>
|
||||
|
||||
<Button
|
||||
variant="link"
|
||||
className="show-button position-absolute end-0 top-50 translate-middle-y me-2"
|
||||
onClick={toggleShow}
|
||||
aria-label="Mostrar contraseña"
|
||||
tabIndex={-1}
|
||||
style={{ zIndex: 2 }}
|
||||
>
|
||||
<FontAwesomeIcon icon={show ? faEyeSlash : faEye} className='fa-lg' />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default PasswordInput;
|
||||
18
src/components/Auth/ProtectedRoute.jsx
Normal file
18
src/components/Auth/ProtectedRoute.jsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Navigate } from "react-router-dom";
|
||||
import { useAuth } from "../../hooks/useAuth.js";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { faSpinner } from "@fortawesome/free-solid-svg-icons";
|
||||
|
||||
const ProtectedRoute = ({ minimumRoles, children }) => {
|
||||
const { authStatus } = useAuth();
|
||||
|
||||
if (authStatus === "checking") return <FontAwesomeIcon icon={faSpinner} />; // o un loader si quieres
|
||||
if (authStatus === "unauthenticated") return <Navigate to="/login" replace />;
|
||||
if (authStatus === "authenticated" && minimumRoles) {
|
||||
const userRole = JSON.parse(localStorage.getItem("user"))?.role;
|
||||
if (!minimumRoles.includes(userRole)) return <Navigate to="/" replace />;
|
||||
}
|
||||
return children;
|
||||
};
|
||||
|
||||
export default ProtectedRoute;
|
||||
114
src/components/Balance/BalancePDF.jsx
Normal file
114
src/components/Balance/BalancePDF.jsx
Normal file
@@ -0,0 +1,114 @@
|
||||
import { Document, Page, Text, View, StyleSheet, Font, Image } from '@react-pdf/renderer';
|
||||
import { format } from 'date-fns';
|
||||
|
||||
Font.register({
|
||||
family: 'Open Sans',
|
||||
fonts: [{ src: '/fonts/OpenSans.ttf', fontWeight: 'normal' }]
|
||||
});
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
page: {
|
||||
padding: 25,
|
||||
fontSize: 12,
|
||||
fontFamily: 'Open Sans',
|
||||
backgroundColor: '#F8F9FA',
|
||||
},
|
||||
headerContainer: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
marginBottom: 25,
|
||||
justifyContent: 'left',
|
||||
},
|
||||
logo: {
|
||||
width: 60,
|
||||
height: 60,
|
||||
},
|
||||
headerText: {
|
||||
flexDirection: 'column',
|
||||
marginLeft: 25,
|
||||
},
|
||||
header: {
|
||||
fontSize: 26,
|
||||
fontWeight: 'bold',
|
||||
color: '#2C3E50',
|
||||
},
|
||||
subHeader: {
|
||||
fontSize: 12,
|
||||
marginTop: 5,
|
||||
color: '#34495E'
|
||||
},
|
||||
sectionTitle: {
|
||||
fontSize: 16,
|
||||
marginTop: 10,
|
||||
marginBottom: 5,
|
||||
color: '#2C3E50',
|
||||
fontWeight: 'bold',
|
||||
},
|
||||
row: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
paddingVertical: 4,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: '#D5D8DC',
|
||||
},
|
||||
label: {
|
||||
fontSize: 11,
|
||||
color: '#566573',
|
||||
},
|
||||
value: {
|
||||
fontSize: 11,
|
||||
fontWeight: 'bold',
|
||||
color: '#2C3E50'
|
||||
}
|
||||
});
|
||||
|
||||
const formatCurrency = (value) =>
|
||||
new Intl.NumberFormat('es-ES', { style: 'currency', currency: 'EUR' }).format(value);
|
||||
|
||||
export const BalancePDF = ({ balance }) => {
|
||||
const {
|
||||
initial_bank,
|
||||
initial_cash,
|
||||
total_bank_expenses,
|
||||
total_cash_expenses,
|
||||
total_bank_incomes,
|
||||
total_cash_incomes,
|
||||
created_at
|
||||
} = balance;
|
||||
|
||||
const final_bank = initial_bank + total_bank_incomes - total_bank_expenses;
|
||||
const final_cash = initial_cash + total_cash_incomes - total_cash_expenses;
|
||||
|
||||
return (
|
||||
<Document>
|
||||
<Page size="A4" style={styles.page}>
|
||||
<View style={styles.headerContainer}>
|
||||
<Image src="/images/logo.png" style={styles.logo} />
|
||||
<View style={styles.headerText}>
|
||||
<Text style={styles.header}>Informe de Balance</Text>
|
||||
<Text style={styles.subHeader}>Asociación Huertos La Salud - Bellavista • Generado el {new Date().toLocaleDateString()} a las {new Date().toLocaleTimeString()}</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<Text style={styles.sectionTitle}>Banco</Text>
|
||||
<View style={styles.row}><Text style={styles.label}>Saldo inicial</Text><Text style={styles.value}>{formatCurrency(initial_bank)}</Text></View>
|
||||
<View style={styles.row}><Text style={styles.label}>Ingresos</Text><Text style={styles.value}>{formatCurrency(total_bank_incomes)}</Text></View>
|
||||
<View style={styles.row}><Text style={styles.label}>Gastos</Text><Text style={styles.value}>{formatCurrency(total_bank_expenses)}</Text></View>
|
||||
|
||||
<Text style={styles.sectionTitle}>Caja</Text>
|
||||
<View style={styles.row}><Text style={styles.label}>Saldo inicial</Text><Text style={styles.value}>{formatCurrency(initial_cash)}</Text></View>
|
||||
<View style={styles.row}><Text style={styles.label}>Ingresos</Text><Text style={styles.value}>{formatCurrency(total_cash_incomes)}</Text></View>
|
||||
<View style={styles.row}><Text style={styles.label}>Gastos</Text><Text style={styles.value}>{formatCurrency(total_cash_expenses)}</Text></View>
|
||||
|
||||
<Text style={styles.sectionTitle}>Total</Text>
|
||||
<View style={styles.row}><Text style={styles.label}>Banco</Text><Text style={styles.value}>{formatCurrency(final_bank)}</Text></View>
|
||||
<View style={styles.row}><Text style={styles.label}>Caja</Text><Text style={styles.value}>{formatCurrency(final_cash)}</Text></View>
|
||||
<View style={styles.row}><Text style={styles.label}>Total</Text><Text style={styles.value}>{formatCurrency(final_bank + final_cash)}</Text></View>
|
||||
|
||||
<Text style={[styles.label, { marginTop: 20 }]}>
|
||||
Última actualización: {format(new Date(created_at), 'dd/MM/yyyy HH:mm')}
|
||||
</Text>
|
||||
</Page>
|
||||
</Document>
|
||||
);
|
||||
};
|
||||
93
src/components/Balance/BalanceReport.jsx
Normal file
93
src/components/Balance/BalanceReport.jsx
Normal file
@@ -0,0 +1,93 @@
|
||||
import { useState } from 'react';
|
||||
import { Card, Button, Row, Col, Container } from 'react-bootstrap';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import {
|
||||
faPiggyBank,
|
||||
faCoins,
|
||||
faArrowDown,
|
||||
faArrowUp,
|
||||
faPrint,
|
||||
faClock
|
||||
} from '@fortawesome/free-solid-svg-icons';
|
||||
import PDFModal from '../PDFModal';
|
||||
import { BalancePDF } from './BalancePDF';
|
||||
import { format } from 'date-fns';
|
||||
import '../../css/BalanceReport.css';
|
||||
|
||||
const formatCurrency = (value) =>
|
||||
new Intl.NumberFormat('es-ES', { style: 'currency', currency: 'EUR' }).format(value);
|
||||
|
||||
const BalanceReport = ({ balance }) => {
|
||||
const [showPDF, setShowPDF] = useState(false);
|
||||
|
||||
const showPDFModal = () => setShowPDF(true);
|
||||
const closePDFModal = () => setShowPDF(false);
|
||||
|
||||
const {
|
||||
initial_bank,
|
||||
initial_cash,
|
||||
total_bank_expenses,
|
||||
total_cash_expenses,
|
||||
total_bank_incomes,
|
||||
total_cash_incomes,
|
||||
created_at
|
||||
} = balance;
|
||||
|
||||
const final_bank = initial_bank + total_bank_incomes - total_bank_expenses;
|
||||
const final_cash = initial_cash + total_cash_incomes - total_cash_expenses;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Container className="my-4">
|
||||
<Card className="balance-report px-4 py-5">
|
||||
<Row className="align-items-center justify-content-between mb-4">
|
||||
<Col xs="12" md="auto" className="text-center text-md-start mb-3 mb-md-0">
|
||||
<h1 className="report-title m-0">📊 Informe de Balance</h1>
|
||||
</Col>
|
||||
<Col xs="12" md="auto" className="text-center text-md-end">
|
||||
<Button className="print-btn" onClick={showPDFModal}>
|
||||
<FontAwesomeIcon icon={faPrint} className="me-2" />
|
||||
Imprimir PDF
|
||||
</Button>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Row className="gy-4">
|
||||
<Col md={6}>
|
||||
<div className="balance-box">
|
||||
<h4><FontAwesomeIcon icon={faPiggyBank} className="me-2" />Banco</h4>
|
||||
<p>Saldo inicial: <span className="balance-value">{formatCurrency(initial_bank)}</span></p>
|
||||
<p><FontAwesomeIcon icon={faArrowUp} className="me-1 text-success" />Ingresos: <span className="balance-value">{formatCurrency(total_bank_incomes)}</span></p>
|
||||
<p><FontAwesomeIcon icon={faArrowDown} className="me-1 text-danger" />Gastos: <span className="balance-value">{formatCurrency(total_bank_expenses)}</span></p>
|
||||
<p className="fw-bold mt-3">💰 Saldo final: {formatCurrency(final_bank)}</p>
|
||||
</div>
|
||||
</Col>
|
||||
|
||||
<Col md={6}>
|
||||
<div className="balance-box">
|
||||
<h4><FontAwesomeIcon icon={faCoins} className="me-2" />Caja</h4>
|
||||
<p>Saldo inicial: <span className="balance-value">{formatCurrency(initial_cash)}</span></p>
|
||||
<p><FontAwesomeIcon icon={faArrowUp} className="me-1 text-success" />Ingresos: <span className="balance-value">{formatCurrency(total_cash_incomes)}</span></p>
|
||||
<p><FontAwesomeIcon icon={faArrowDown} className="me-1 text-danger" />Gastos: <span className="balance-value">{formatCurrency(total_cash_expenses)}</span></p>
|
||||
<p className="fw-bold mt-3">💵 Saldo final: {formatCurrency(final_cash)}</p>
|
||||
</div>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Row className="mt-4">
|
||||
<Col className="text-end balance-timestamp">
|
||||
<FontAwesomeIcon icon={faClock} className="me-2" />
|
||||
Última actualización: {format(new Date(created_at), 'dd/MM/yyyy HH:mm')}
|
||||
</Col>
|
||||
</Row>
|
||||
</Card>
|
||||
</Container>
|
||||
|
||||
<PDFModal show={showPDF} onClose={closePDFModal} title="Vista previa del PDF">
|
||||
<BalancePDF balance={balance} />
|
||||
</PDFModal>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default BalanceReport;
|
||||
15
src/components/ContentWrapper.jsx
Normal file
15
src/components/ContentWrapper.jsx
Normal file
@@ -0,0 +1,15 @@
|
||||
import PropTypes from 'prop-types';
|
||||
|
||||
const ContentWrapper = ({ children }) => {
|
||||
return (
|
||||
<div className="container-xl">
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
ContentWrapper.propTypes = {
|
||||
children: PropTypes.node.isRequired,
|
||||
}
|
||||
|
||||
export default ContentWrapper;
|
||||
105
src/components/Correo/ComposeMailModal.jsx
Normal file
105
src/components/Correo/ComposeMailModal.jsx
Normal file
@@ -0,0 +1,105 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Modal, Button, Form } from 'react-bootstrap';
|
||||
import 'bootstrap/dist/css/bootstrap.min.css';
|
||||
|
||||
export default function ComposeMailModal({ isOpen, onClose, onSend }) {
|
||||
const [formData, setFormData] = useState({
|
||||
from: '',
|
||||
to: [],
|
||||
subject: '',
|
||||
content: '',
|
||||
attachments: []
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
const user = JSON.parse(localStorage.getItem("user"));
|
||||
const email = user?.email || '';
|
||||
setFormData((prev) => ({ ...prev, from: email }));
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
const handleChange = (e) => {
|
||||
const { name, value } = e.target;
|
||||
|
||||
if (name === 'to') {
|
||||
const toArray = value
|
||||
.split(',')
|
||||
.map((email) => email.trim())
|
||||
.filter((email) => email !== '');
|
||||
setFormData({ ...formData, to: toArray });
|
||||
} else {
|
||||
setFormData({ ...formData, [name]: value });
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileChange = (e) => {
|
||||
setFormData({ ...formData, attachments: Array.from(e.target.files) });
|
||||
};
|
||||
|
||||
const handleSubmit = (e) => {
|
||||
e.preventDefault();
|
||||
onSend(formData);
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal show={isOpen} onHide={onClose} centered>
|
||||
<Modal.Header closeButton>
|
||||
<Modal.Title>Redactar Correo</Modal.Title>
|
||||
</Modal.Header>
|
||||
<Modal.Body>
|
||||
<Form onSubmit={handleSubmit}>
|
||||
<Form.Group className="mb-3" controlId="formTo">
|
||||
<Form.Label>Para:</Form.Label>
|
||||
<Form.Control
|
||||
type="text"
|
||||
name="to"
|
||||
value={formData.to.join(', ')}
|
||||
onChange={handleChange}
|
||||
placeholder="Separar múltiples correos con comas"
|
||||
required
|
||||
/>
|
||||
</Form.Group>
|
||||
<Form.Group className="mb-3" controlId="formSubject">
|
||||
<Form.Label>Asunto:</Form.Label>
|
||||
<Form.Control
|
||||
type="text"
|
||||
name="subject"
|
||||
value={formData.subject}
|
||||
onChange={handleChange}
|
||||
required
|
||||
/>
|
||||
</Form.Group>
|
||||
<Form.Group className="mb-3" controlId="formContent">
|
||||
<Form.Label>Contenido:</Form.Label>
|
||||
<Form.Control
|
||||
as="textarea"
|
||||
rows={5}
|
||||
name="content"
|
||||
value={formData.content}
|
||||
onChange={handleChange}
|
||||
required
|
||||
/>
|
||||
</Form.Group>
|
||||
<Form.Group className="mb-3" controlId="formAttachments">
|
||||
<Form.Label>Adjuntos:</Form.Label>
|
||||
<Form.Control
|
||||
type="file"
|
||||
multiple
|
||||
onChange={handleFileChange}
|
||||
/>
|
||||
</Form.Group>
|
||||
</Form>
|
||||
</Modal.Body>
|
||||
<Modal.Footer>
|
||||
<Button variant="secondary" onClick={onClose}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button variant="primary" onClick={handleSubmit}>
|
||||
Enviar
|
||||
</Button>
|
||||
</Modal.Footer>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
26
src/components/Correo/MailList.jsx
Normal file
26
src/components/Correo/MailList.jsx
Normal file
@@ -0,0 +1,26 @@
|
||||
import React from 'react';
|
||||
import '../../css/MailList.css';
|
||||
|
||||
export default function MailList({ emails, onSelect, selectedEmail, className = '' }) {
|
||||
return (
|
||||
<div className={`mail-list ${className}`}>
|
||||
{emails.map((mail, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className={`mail-item rounded-4 mb-2 ${selectedEmail?.index === index ? 'active' : ''}`}
|
||||
onClick={() => onSelect(mail, index)}
|
||||
>
|
||||
<div className="subject">{mail.subject || "(Sin asunto)"}</div>
|
||||
<div className="preview">
|
||||
{!mail.content && "Sin contenido"}
|
||||
{mail.content.includes("<") ? (
|
||||
"Contenido HTML personalizado"
|
||||
) : (
|
||||
mail.content?.slice(0, 100)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
20
src/components/Correo/MailListMobile.jsx
Normal file
20
src/components/Correo/MailListMobile.jsx
Normal file
@@ -0,0 +1,20 @@
|
||||
import React from 'react';
|
||||
import '../../css/MailListMobile.css';
|
||||
|
||||
export default function MailListMobile({ emails, onSelect, selectedEmail, className = '' }) {
|
||||
return (
|
||||
<div className={`mail-list-mobile ${className}`}>
|
||||
{emails.map((mail, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className={`mail-item-mobile rounded-4 mb-2 ${selectedEmail?.index === index ? 'active' : ''}`}
|
||||
onClick={() => onSelect(mail, index)}
|
||||
>
|
||||
<div className="subject">{mail.subject || "(Sin asunto)"}</div>
|
||||
<div className="preview">{mail.content?.slice(0, 100) || "Sin contenido"}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
22
src/components/Correo/MailToolbar.jsx
Normal file
22
src/components/Correo/MailToolbar.jsx
Normal file
@@ -0,0 +1,22 @@
|
||||
import React from 'react';
|
||||
import '../../css/MailToolbar.css';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { faPlus, faInbox, faPaperPlane, faTrash, faPen } from '@fortawesome/free-solid-svg-icons';
|
||||
|
||||
export default function MailToolbar({ onCompose }) {
|
||||
return (
|
||||
<div className="mail-toolbar-wrapper sticky-top">
|
||||
<div className="mail-toolbar">
|
||||
<div className="toolbar-icons">
|
||||
<FontAwesomeIcon icon={faInbox} title="Entrada" className='text-success' />
|
||||
<FontAwesomeIcon icon={faPaperPlane} title="Enviados" className='text-primary' />
|
||||
<FontAwesomeIcon icon={faPen} title="Borradores" className='text-warning' />
|
||||
<FontAwesomeIcon icon={faTrash} title="Spam" className='text-danger' />
|
||||
</div>
|
||||
<button className="toolbar-btn" onClick={onCompose}>
|
||||
<FontAwesomeIcon icon={faPlus} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
171
src/components/Correo/MailView.jsx
Normal file
171
src/components/Correo/MailView.jsx
Normal file
@@ -0,0 +1,171 @@
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import '../../css/MailView.css';
|
||||
import { faEnvelopeOpenText } from '@fortawesome/free-solid-svg-icons';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
|
||||
export default function MailView({ email }) {
|
||||
const mailContentRef = useRef(null);
|
||||
|
||||
const getFileIcon = (filename) => {
|
||||
if (!filename) return '/images/icons/filetype/file_64.svg';
|
||||
|
||||
const extension = filename.split('.').pop()?.toLowerCase();
|
||||
|
||||
switch (extension) {
|
||||
case 'pdf':
|
||||
return '/images/icons/filetype/pdf_64.svg';
|
||||
case 'jpg':
|
||||
case 'jpeg':
|
||||
return '/images/icons/filetype/jpg_64.svg';
|
||||
case 'png':
|
||||
return '/images/icons/filetype/png_64.svg';
|
||||
case 'mp4':
|
||||
case 'avi':
|
||||
case 'mov':
|
||||
return '/images/icons/filetype/mp4_64.svg';
|
||||
case 'txt':
|
||||
case 'text':
|
||||
return '/images/icons/filetype/txt_64.svg';
|
||||
default:
|
||||
return '/images/icons/filetype/file_64.svg';
|
||||
}
|
||||
};
|
||||
|
||||
const processTextContent = (text) => {
|
||||
if (!text) return "Sin contenido";
|
||||
|
||||
const urlRegex = /(https?:\/\/[^\s]+)/g;
|
||||
const emailRegex = /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)/g;
|
||||
|
||||
return text
|
||||
.replace(urlRegex, '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>')
|
||||
.replace(emailRegex, '<a href="mailto:$1">$1</a>')
|
||||
.replace(/\n/g, '<br>');
|
||||
};
|
||||
|
||||
const processHtmlContent = (html) => {
|
||||
if (!html) return "Sin contenido";
|
||||
|
||||
let processedHtml = html;
|
||||
|
||||
processedHtml = processedHtml.replace(
|
||||
/<a([^>]*?)(?:\s+target="[^"]*")?([^>]*?)>/g,
|
||||
'<a$1 target="_blank" rel="noopener noreferrer"$2>'
|
||||
);
|
||||
|
||||
processedHtml = processedHtml.replace(
|
||||
/<img([^>]*?)>/g,
|
||||
'<img$1 style="max-width: 100%; height: auto; border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">'
|
||||
);
|
||||
|
||||
return processedHtml;
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const currentRef = mailContentRef.current;
|
||||
|
||||
if (currentRef) {
|
||||
const handleLinkClick = (e) => {
|
||||
const link = e.target.closest('a');
|
||||
if (link && link.href) {
|
||||
e.preventDefault();
|
||||
window.open(link.href, '_blank', 'noopener,noreferrer');
|
||||
}
|
||||
};
|
||||
|
||||
const images = currentRef.querySelectorAll('img');
|
||||
images.forEach(img => {
|
||||
img.style.maxWidth = '100%';
|
||||
img.style.height = 'auto';
|
||||
img.style.borderRadius = '4px';
|
||||
img.style.boxShadow = '0 2px 8px rgba(0,0,0,0.1)';
|
||||
|
||||
if (!img.getAttribute('loading')) {
|
||||
img.setAttribute('loading', 'lazy');
|
||||
}
|
||||
});
|
||||
|
||||
currentRef.addEventListener('click', handleLinkClick);
|
||||
|
||||
return () => {
|
||||
if (currentRef) {
|
||||
currentRef.removeEventListener('click', handleLinkClick);
|
||||
}
|
||||
};
|
||||
}
|
||||
}, [email]);
|
||||
|
||||
if (!email) {
|
||||
return (
|
||||
<div className='d-flex display-4 flex-column justify-content-center align-items-center vh-100 w-100'>
|
||||
<FontAwesomeIcon icon={faEnvelopeOpenText} className="me-2" />
|
||||
<h3 className='display-4'>No hay correo seleccionado</h3>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const from = email.from || "Remitente desconocido";
|
||||
const date = new Date(email.date).toLocaleString();
|
||||
const to = (email.to || []).join(', ');
|
||||
|
||||
const isHtml = email.content && (
|
||||
email.content.includes('<html') ||
|
||||
email.content.includes('<body') ||
|
||||
email.content.includes('<div') ||
|
||||
email.content.includes('<p>') ||
|
||||
email.content.includes('<br') ||
|
||||
email.content.includes('<img') ||
|
||||
email.content.includes('<a href') ||
|
||||
email.content.includes('<table') ||
|
||||
email.content.includes('<ul') ||
|
||||
email.content.includes('<ol') ||
|
||||
/<[a-z][\s\S]*>/i.test(email.content)
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="mail-view">
|
||||
<div className="mail-header">
|
||||
<h2>{email.subject || "(Sin asunto)"}</h2>
|
||||
<div className="mail-meta">
|
||||
<span><strong>De:</strong> {from}</span><br />
|
||||
<span><strong>Para:</strong> {to}</span><br />
|
||||
<span><strong>Fecha:</strong> {date}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mail-body">
|
||||
<div
|
||||
ref={mailContentRef}
|
||||
className="mail-content"
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: isHtml
|
||||
? processHtmlContent(email.content)
|
||||
: processTextContent(email.content || "")
|
||||
}}
|
||||
/>
|
||||
|
||||
{email.attachments && email.attachments.length > 0 && (
|
||||
<div className="mail-attachments mt-3">
|
||||
<h5>Adjuntos:</h5>
|
||||
<ul>
|
||||
{email.attachments.map((a, i) => (
|
||||
<li key={i}>
|
||||
<a href={a.url} target="_blank" rel="noopener noreferrer">
|
||||
<img
|
||||
src={getFileIcon(a.name)}
|
||||
alt="File icon"
|
||||
width="16"
|
||||
height="16"
|
||||
style={{ marginRight: '8px' }}
|
||||
/>
|
||||
{a.name}
|
||||
{a.size && <span className="attachment-size"> ({a.size})</span>}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
43
src/components/Correo/MobileToolbar.jsx
Normal file
43
src/components/Correo/MobileToolbar.jsx
Normal file
@@ -0,0 +1,43 @@
|
||||
import React from 'react';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import {
|
||||
faInbox, faPaperPlane, faPenFancy, faTrash,
|
||||
faPlus, faArrowLeft
|
||||
} from '@fortawesome/free-solid-svg-icons';
|
||||
import '../../css/MobileToolbar.css';
|
||||
|
||||
export default function MobileToolbar({ isViewingMail, onBack, onCompose, className }) {
|
||||
return (
|
||||
<div className={`search-toolbar-wrapper ${className}`}>
|
||||
<div className="search-toolbar mobile-toolbar-content">
|
||||
{!isViewingMail ? (
|
||||
<>
|
||||
<div className="toolbar-icons mobile-toolbar-icons">
|
||||
<button className="icon-btn" title="Entrada">
|
||||
<FontAwesomeIcon icon={faInbox} />
|
||||
</button>
|
||||
<button className="icon-btn" title="Enviados">
|
||||
<FontAwesomeIcon icon={faPaperPlane} />
|
||||
</button>
|
||||
<button className="icon-btn" title="Borradores">
|
||||
<FontAwesomeIcon icon={faPenFancy} />
|
||||
</button>
|
||||
<button className="icon-btn" title="Spam">
|
||||
<FontAwesomeIcon icon={faTrash} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="toolbar-buttons">
|
||||
<button className="btn icon-btn" onClick={onCompose} title="Redactar">
|
||||
<FontAwesomeIcon icon={faPlus} />
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<button className="btn icon-btn" onClick={onBack} title="Volver">
|
||||
<FontAwesomeIcon icon={faArrowLeft} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
52
src/components/Correo/Sidebar.jsx
Normal file
52
src/components/Correo/Sidebar.jsx
Normal file
@@ -0,0 +1,52 @@
|
||||
import React, { useState } from 'react';
|
||||
import '../../css/Sidebar.css';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { faEdit, faExclamationCircle, faInbox, faPaperPlane, faPen, faTrash } from '@fortawesome/free-solid-svg-icons';
|
||||
import ComposeMailModal from './ComposeMailModal';
|
||||
|
||||
|
||||
export default function Sidebar({ onFolderChange, onMailSend }) {
|
||||
const [isComposeOpen, setIsComposeOpen] = useState(false);
|
||||
|
||||
const handleComposeOpen = () => setIsComposeOpen(true);
|
||||
const handleComposeClose = () => setIsComposeOpen(false);
|
||||
const handleSendMail = (mailData) => {
|
||||
onMailSend(mailData);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="sidebar">
|
||||
<button className="compose-btn" onClick={handleComposeOpen}>
|
||||
<FontAwesomeIcon icon={faEdit} className="me-2" />
|
||||
Redactar
|
||||
</button>
|
||||
<nav>
|
||||
<a href="#" onClick={() => onFolderChange("INBOX")}>
|
||||
<FontAwesomeIcon icon={faInbox} className="me-2" />
|
||||
Bandeja de entrada
|
||||
</a>
|
||||
<a href="#" onClick={() => onFolderChange("Sent")}>
|
||||
<FontAwesomeIcon icon={faPaperPlane} className="me-2" />
|
||||
Enviados
|
||||
</a>
|
||||
<a className='disabled' href="#" onClick={() => onFolderChange("Drafts")}>
|
||||
<FontAwesomeIcon icon={faPen} className="me-2" />
|
||||
Borradores
|
||||
</a>
|
||||
<a className='disabled' href="#" onClick={() => onFolderChange("Spam")}>
|
||||
<FontAwesomeIcon icon={faExclamationCircle} className="me-2" />
|
||||
Spam
|
||||
</a>
|
||||
<a className='disabled' href="#" onClick={() => onFolderChange("Trash")}>
|
||||
<FontAwesomeIcon icon={faTrash} className="me-2" />
|
||||
Papelera
|
||||
</a>
|
||||
</nav>
|
||||
<ComposeMailModal
|
||||
isOpen={isComposeOpen}
|
||||
onClose={handleComposeClose}
|
||||
onSend={handleSendMail}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
47
src/components/CustomCarousel.jsx
Normal file
47
src/components/CustomCarousel.jsx
Normal file
@@ -0,0 +1,47 @@
|
||||
import Slider from 'react-slick';
|
||||
import '../css/CustomCarousel.css';
|
||||
|
||||
const CustomCarousel = ({ images }) => {
|
||||
const settings = {
|
||||
dots: false,
|
||||
infinite: true,
|
||||
speed: 500,
|
||||
slidesToShow: 2,
|
||||
slidesToScroll: 1,
|
||||
arrows: false,
|
||||
autoplay: true,
|
||||
autoplaySpeed: 3000,
|
||||
responsive: [
|
||||
{
|
||||
breakpoint: 768, // móviles
|
||||
settings: {
|
||||
slidesToShow: 1,
|
||||
arrows: false,
|
||||
autoplay: true,
|
||||
autoplaySpeed: 3000,
|
||||
dots: false,
|
||||
infinite: true,
|
||||
speed: 500
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="my-4">
|
||||
<Slider {...settings}>
|
||||
{images.map((src, index) => (
|
||||
<div key={index} className='carousel-img-wrapper'>
|
||||
<img
|
||||
src={src}
|
||||
alt={`slide-${index}`}
|
||||
className="carousel-img"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</Slider>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default CustomCarousel;
|
||||
15
src/components/CustomContainer.jsx
Normal file
15
src/components/CustomContainer.jsx
Normal file
@@ -0,0 +1,15 @@
|
||||
import PropTypes from 'prop-types';
|
||||
|
||||
const CustomContainer = ({ children }) => {
|
||||
return (
|
||||
<main className="px-4 py-5">
|
||||
{children}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
CustomContainer.propTypes = {
|
||||
children: PropTypes.node.isRequired,
|
||||
}
|
||||
|
||||
export default CustomContainer;
|
||||
26
src/components/CustomModal.jsx
Normal file
26
src/components/CustomModal.jsx
Normal file
@@ -0,0 +1,26 @@
|
||||
import { faXmark } from "@fortawesome/free-solid-svg-icons";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { Modal, Button } from "react-bootstrap";
|
||||
|
||||
const CustomModal = ({ show, onClose, title, children }) => {
|
||||
return (
|
||||
<Modal show={show} onHide={onClose} size="xl" centered>
|
||||
<Modal.Header className='justify-content-between rounded-top-4'>
|
||||
<Modal.Title>{title}</Modal.Title>
|
||||
<Button variant='transparent' onClick={onClose}>
|
||||
<FontAwesomeIcon icon={faXmark} className='close-button fa-xl' />
|
||||
</Button>
|
||||
</Modal.Header>
|
||||
<Modal.Body className="rounded-bottom-4 p-0"
|
||||
style={{
|
||||
maxHeight: '80vh',
|
||||
overflowY: 'auto',
|
||||
padding: '1rem',
|
||||
}}>
|
||||
{children}
|
||||
</Modal.Body>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
export default CustomModal;
|
||||
60
src/components/Documentacion/File.jsx
Normal file
60
src/components/Documentacion/File.jsx
Normal file
@@ -0,0 +1,60 @@
|
||||
import { faTrashAlt } from "@fortawesome/free-regular-svg-icons";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { Card, Button, OverlayTrigger, Tooltip } from "react-bootstrap";
|
||||
import '../../css/File.css';
|
||||
|
||||
const File = ({ file, onDelete }) => {
|
||||
const getIcon = (type) => {
|
||||
const dir = "/images/icons/filetype/";
|
||||
switch (type) {
|
||||
case "image/jpeg":
|
||||
return dir + "jpg_64.svg";
|
||||
case "image/png":
|
||||
return dir + "png_64.svg";
|
||||
case "video/mp4":
|
||||
return dir + "mp4_64.svg";
|
||||
case "application/pdf":
|
||||
return dir + "pdf_64.svg";
|
||||
case "text/plain":
|
||||
return dir + "txt_64.svg";
|
||||
default:
|
||||
return dir + "file_64.svg";
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card
|
||||
className="file-card col-sm-3 col-lg-2 col-xxl-1 m-0 p-0 position-relative text-decoration-none bg-transparent"
|
||||
onClick={() => window.open(`https://miarma.net/files/huertos/${file.file_name}`, "_blank")}
|
||||
>
|
||||
<Card.Body className="text-center">
|
||||
<img
|
||||
src={getIcon(file.mime_type)}
|
||||
alt={file.file_name}
|
||||
className="img-fluid mb-2"
|
||||
/>
|
||||
<OverlayTrigger
|
||||
placement="bottom"
|
||||
overlay={<Tooltip>{file.file_name}</Tooltip>}
|
||||
>
|
||||
<p className="m-0 p-0 text-truncate">{file.file_name}</p>
|
||||
</OverlayTrigger>
|
||||
</Card.Body>
|
||||
|
||||
<Button
|
||||
variant="transparent"
|
||||
size="md"
|
||||
color="text-danger"
|
||||
className="delete-btn position-absolute top-0 end-0 m-0"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onDelete?.(file);
|
||||
}}
|
||||
>
|
||||
<FontAwesomeIcon icon={faTrashAlt} />
|
||||
</Button>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
export default File;
|
||||
106
src/components/Documentacion/FileUpload.jsx
Normal file
106
src/components/Documentacion/FileUpload.jsx
Normal file
@@ -0,0 +1,106 @@
|
||||
import { forwardRef, useImperativeHandle, useRef, useState } from "react";
|
||||
import { Card, CloseButton } from "react-bootstrap";
|
||||
import "../../css/FileUpload.css";
|
||||
|
||||
const MAX_FILE_SIZE_MB = 10;
|
||||
|
||||
const FileUpload = forwardRef(({ onFilesSelected }, ref) => {
|
||||
const fileInputRef = useRef();
|
||||
const [highlight, setHighlight] = useState(false);
|
||||
const [selectedFiles, setSelectedFiles] = useState([]);
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
resetSelectedFiles: () => {
|
||||
setSelectedFiles([]);
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = null; // limpia input real
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
const handleFiles = (files) => {
|
||||
const validFiles = Array.from(files).filter(
|
||||
(file) => file.size <= MAX_FILE_SIZE_MB * 1024 * 1024
|
||||
);
|
||||
setSelectedFiles(validFiles);
|
||||
if (onFilesSelected) onFilesSelected(validFiles);
|
||||
};
|
||||
|
||||
const handleInputChange = (e) => {
|
||||
handleFiles(e.target.files);
|
||||
};
|
||||
|
||||
const handleDrop = (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setHighlight(false);
|
||||
handleFiles(e.dataTransfer.files);
|
||||
};
|
||||
|
||||
const handleDragOver = (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setHighlight(true);
|
||||
};
|
||||
|
||||
const handleDragLeave = () => {
|
||||
setHighlight(false);
|
||||
};
|
||||
|
||||
const openFileDialog = () => {
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
const removeFile = (index) => {
|
||||
const updated = [...selectedFiles];
|
||||
updated.splice(index, 1);
|
||||
setSelectedFiles(updated);
|
||||
if (onFilesSelected) onFilesSelected(updated);
|
||||
};
|
||||
|
||||
return (
|
||||
<Card
|
||||
className={`upload-card shadow-sm mb-4 ${highlight ? "highlight" : ""}`}
|
||||
onClick={openFileDialog}
|
||||
onDrop={handleDrop}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
role="button"
|
||||
>
|
||||
<Card.Body className="text-center">
|
||||
<h2 className="mb-3">📎 Subir archivo</h2>
|
||||
<p>
|
||||
Arrastra o haz click para seleccionar archivos (Máx. 10MB)
|
||||
</p>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".pdf"
|
||||
multiple
|
||||
className="d-none"
|
||||
onChange={handleInputChange}
|
||||
/>
|
||||
{selectedFiles.length > 0 && (
|
||||
<ul className="file-list text-start mt-4 px-3">
|
||||
{selectedFiles.map((file, idx) => (
|
||||
<li
|
||||
key={idx}
|
||||
className="d-flex justify-content-between align-items-center mb-2"
|
||||
>
|
||||
<span>📄 {file.name}</span>
|
||||
<CloseButton
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
removeFile(idx);
|
||||
}}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Card.Body>
|
||||
</Card>
|
||||
);
|
||||
});
|
||||
|
||||
export default FileUpload;
|
||||
55
src/components/Footer.jsx
Normal file
55
src/components/Footer.jsx
Normal file
@@ -0,0 +1,55 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { faLocationDot, faEnvelope } from '@fortawesome/free-solid-svg-icons';
|
||||
import '../css/Footer.css';
|
||||
|
||||
const Footer = () => {
|
||||
const [heart, setHeart] = useState('💜');
|
||||
|
||||
useEffect(() => {
|
||||
const hearts = ["❤️", "💛", "🧡", "💚", "💙", "💜"];
|
||||
const randomHeart = () => hearts[Math.floor(Math.random() * hearts.length)];
|
||||
|
||||
const interval = setInterval(() => {
|
||||
setHeart(randomHeart());
|
||||
}, 3000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<footer className="footer d-flex flex-column align-items-center gap-5 pt-5 px-4">
|
||||
<div className="footer-columns w-100" style={{ maxWidth: '900px' }}>
|
||||
<div className="footer-column">
|
||||
<h4 className="footer-title">Datos de Contacto</h4>
|
||||
<div className="contact-info p-4">
|
||||
<a
|
||||
href="https://www.google.com/maps?q=Calle+Cronos+S/N,+Bellavista,+Sevilla,+41014"
|
||||
target="_blank"
|
||||
className='text-break d-block'
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<FontAwesomeIcon icon={faLocationDot} className="fa-icon me-2 " />
|
||||
Calle Cronos S/N, Bellavista, Sevilla, 41014
|
||||
</a>
|
||||
<a href="mailto:huertoslasaludbellavista@gmail.com" className="text-break d-block">
|
||||
<FontAwesomeIcon icon={faEnvelope} className="fa-icon me-2" />
|
||||
huertoslasaludbellavista@gmail.com
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="footer-bottom w-100 py-5 text-center">
|
||||
<h6 id="devd" className='m-0'>
|
||||
Hecho con <span className="heart-anim">{heart}</span> por{' '}
|
||||
<a href="https://gallardo.dev" target="_blank" rel="noopener noreferrer">
|
||||
Gallardo7761
|
||||
</a>
|
||||
</h6>
|
||||
</div>
|
||||
</footer>
|
||||
);
|
||||
};
|
||||
|
||||
export default Footer;
|
||||
196
src/components/Gastos/GastoCard.jsx
Normal file
196
src/components/Gastos/GastoCard.jsx
Normal file
@@ -0,0 +1,196 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import {
|
||||
Card, Badge, Button, Form
|
||||
} from 'react-bootstrap';
|
||||
import PropTypes from 'prop-types';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import {
|
||||
faMoneyBillWave,
|
||||
faTruck,
|
||||
faReceipt,
|
||||
faTrash,
|
||||
faEdit,
|
||||
faTimes,
|
||||
faEllipsisVertical
|
||||
} from '@fortawesome/free-solid-svg-icons';
|
||||
import { motion as _motion } from 'framer-motion';
|
||||
import AnimatedDropdown from '../../components/AnimatedDropdown';
|
||||
import { useTheme } from '../../hooks/useTheme';
|
||||
import '../../css/IngresoCard.css';
|
||||
import { CONSTANTS } from '../../util/constants';
|
||||
import { DateParser } from '../../util/parsers/dateParser';
|
||||
import { renderErrorAlert } from '../../util/alertHelpers';
|
||||
import { getNowAsLocalDatetime } from '../../util/date';
|
||||
import SpanishDateTimePicker from '../SpanishDateTimePicker';
|
||||
|
||||
const MotionCard = _motion.create(Card);
|
||||
|
||||
const getTypeLabel = (type) => type === CONSTANTS.PAYMENT_TYPE_BANK ? "Banco" : "Caja";
|
||||
const getTypeColor = (type, theme) => type === 0 ? "primary" : theme === "light" ? "dark" : "light";
|
||||
const getTypeTextColor = (type, theme) => type === 0 ? "light" : theme === "light" ? "light" : "dark";
|
||||
|
||||
const getPFP = (tipo) => {
|
||||
const base = '/images/icons/';
|
||||
const map = {
|
||||
1: 'cash.svg',
|
||||
0: 'bank.svg'
|
||||
};
|
||||
return base + (map[tipo] || 'farmer.svg');
|
||||
};
|
||||
|
||||
const GastoCard = ({ gasto, isNew = false, onCreate, onUpdate, onDelete, onCancel, error, onClearError }) => {
|
||||
const createMode = isNew;
|
||||
const [editMode, setEditMode] = useState(createMode);
|
||||
const { theme } = useTheme();
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
concept: gasto.concept || '',
|
||||
amount: gasto.amount || 0,
|
||||
supplier: gasto.supplier || '',
|
||||
invoice: gasto.invoice || '',
|
||||
type: gasto.type ?? 0,
|
||||
created_at: gasto.created_at?.slice(0, 16) || (isNew ? getNowAsLocalDatetime() : ''),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!editMode) {
|
||||
setFormData({
|
||||
concept: gasto.concept || '',
|
||||
amount: gasto.amount || 0,
|
||||
supplier: gasto.supplier || '',
|
||||
invoice: gasto.invoice || '',
|
||||
type: gasto.type ?? 0,
|
||||
created_at: gasto.created_at?.slice(0, 16) || (isNew ? getNowAsLocalDatetime() : ''),
|
||||
});
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [gasto, editMode]);
|
||||
|
||||
const handleChange = (field, value) => setFormData(prev => ({ ...prev, [field]: value }));
|
||||
|
||||
const handleDelete = () => typeof onDelete === 'function' && onDelete(gasto.expense_id);
|
||||
|
||||
const handleCancel = () => {
|
||||
if (onClearError) onClearError();
|
||||
if (isNew && typeof onCancel === 'function') return onCancel();
|
||||
setEditMode(false);
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
if (onClearError) onClearError();
|
||||
const newExpense = { ...gasto, ...formData };
|
||||
if (createMode && typeof onCreate === 'function') return onCreate(newExpense);
|
||||
if (typeof onUpdate === 'function') return onUpdate(newExpense, gasto.expense_id);
|
||||
};
|
||||
|
||||
return (
|
||||
<MotionCard className="ingreso-card shadow-sm rounded-4 border-0 h-100">
|
||||
<Card.Header className="d-flex justify-content-between align-items-center rounded-top-4 bg-light-green">
|
||||
<div className="d-flex align-items-center">
|
||||
<img src={getPFP(formData.type)} width={36} alt="Tipo de gasto" className='me-3' />
|
||||
<div className="d-flex flex-column">
|
||||
<span className="fw-bold">
|
||||
{editMode ? (
|
||||
<Form.Control
|
||||
className="themed-input"
|
||||
size="sm"
|
||||
value={formData.concept}
|
||||
onChange={(e) => handleChange('concept', e.target.value.toUpperCase())}
|
||||
/>
|
||||
) : formData.concept}
|
||||
</span>
|
||||
<small>
|
||||
{editMode ? (
|
||||
<SpanishDateTimePicker
|
||||
selected={new Date(formData.created_at)}
|
||||
onChange={(date) =>
|
||||
handleChange('created_at', date.toISOString().slice(0, 16))
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
DateParser.isoToStringWithTime(formData.created_at)
|
||||
)}
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!createMode && !editMode && (
|
||||
<AnimatedDropdown className='end-0' icon={<FontAwesomeIcon icon={faEllipsisVertical} className="fa-xl text-dark" />}>
|
||||
{({ closeDropdown }) => (
|
||||
<>
|
||||
<div className="dropdown-item d-flex align-items-center" onClick={() => { setEditMode(true); closeDropdown(); }}>
|
||||
<FontAwesomeIcon icon={faEdit} className="me-2" />Editar
|
||||
</div>
|
||||
<div className="dropdown-item d-flex align-items-center text-danger" onClick={() => { handleDelete(); closeDropdown(); }}>
|
||||
<FontAwesomeIcon icon={faTrash} className="me-2" />Eliminar
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</AnimatedDropdown>
|
||||
)}
|
||||
</Card.Header>
|
||||
|
||||
|
||||
<Card.Body>
|
||||
{(editMode || createMode) && renderErrorAlert(error)}
|
||||
|
||||
<Card.Text className="mb-2">
|
||||
<FontAwesomeIcon icon={faMoneyBillWave} className="me-2" />
|
||||
<strong>Importe:</strong>{' '}
|
||||
{editMode ? (
|
||||
<Form.Control className="themed-input" size="sm" type="number" step="0.01" value={formData.amount} onChange={(e) => handleChange('amount', parseFloat(e.target.value))} style={{ maxWidth: '150px', display: 'inline-block' }} />
|
||||
) : `${formData.amount.toFixed(2)} €`}
|
||||
</Card.Text>
|
||||
|
||||
<Card.Text className="mb-2">
|
||||
<FontAwesomeIcon icon={faTruck} className="me-2" />
|
||||
<strong>Proveedor:</strong>{' '}
|
||||
{editMode ? (
|
||||
<Form.Control className="themed-input" size="sm" type="text" value={formData.supplier} onChange={(e) => handleChange('supplier', e.target.value)} />
|
||||
) : formData.supplier}
|
||||
</Card.Text>
|
||||
|
||||
<Card.Text className="mb-2">
|
||||
<FontAwesomeIcon icon={faReceipt} className="me-2" />
|
||||
<strong>Factura:</strong>{' '}
|
||||
{editMode ? (
|
||||
<Form.Control className="themed-input" size="sm" type="text" value={formData.invoice} onChange={(e) => handleChange('invoice', e.target.value)} />
|
||||
) : formData.invoice}
|
||||
</Card.Text>
|
||||
|
||||
{editMode ? (
|
||||
<>
|
||||
<Form.Group className="mb-3">
|
||||
<Form.Label>Tipo de gasto</Form.Label>
|
||||
<Form.Select className='themed-input' size="sm" value={formData.type} onChange={(e) => handleChange('type', parseInt(e.target.value))}>
|
||||
<option value={0}>Banco</option>
|
||||
<option value={1}>Caja</option>
|
||||
</Form.Select>
|
||||
</Form.Group>
|
||||
<div className="d-flex justify-content-end gap-2">
|
||||
<Button variant="secondary" size="sm" onClick={handleCancel}><FontAwesomeIcon icon={faTimes} /> Cancelar</Button>
|
||||
<Button variant="primary" size="sm" onClick={handleSave}>Guardar</Button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="text-end">
|
||||
<Badge bg={getTypeColor(formData.type, theme)} text={getTypeTextColor(formData.type, theme)}>
|
||||
{getTypeLabel(formData.type)}
|
||||
</Badge>
|
||||
</div>
|
||||
)}
|
||||
</Card.Body>
|
||||
</MotionCard>
|
||||
);
|
||||
};
|
||||
|
||||
GastoCard.propTypes = {
|
||||
gasto: PropTypes.object.isRequired,
|
||||
isNew: PropTypes.bool,
|
||||
onCreate: PropTypes.func,
|
||||
onUpdate: PropTypes.func,
|
||||
onDelete: PropTypes.func,
|
||||
onCancel: PropTypes.func
|
||||
};
|
||||
|
||||
export default GastoCard;
|
||||
68
src/components/Gastos/GastosFilter.jsx
Normal file
68
src/components/Gastos/GastosFilter.jsx
Normal file
@@ -0,0 +1,68 @@
|
||||
import PropTypes from 'prop-types';
|
||||
|
||||
const GastosFilter = ({ filters, onChange }) => {
|
||||
const handleCheckboxChange = (key) => {
|
||||
if (key === 'todos') {
|
||||
const newValue = !filters.todos;
|
||||
onChange({
|
||||
todos: newValue,
|
||||
banco: newValue,
|
||||
caja: newValue
|
||||
});
|
||||
} else {
|
||||
const updated = { ...filters, [key]: !filters[key] };
|
||||
const allTrue = Object.entries(updated)
|
||||
.filter(([k]) => k !== 'todos')
|
||||
.every(([, v]) => v === true);
|
||||
|
||||
updated.todos = allTrue;
|
||||
onChange(updated);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="dropdown-item d-flex align-items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="todosCheck"
|
||||
className="me-2"
|
||||
checked={filters.todos}
|
||||
onChange={() => handleCheckboxChange('todos')}
|
||||
/>
|
||||
<label htmlFor="todosCheck" className="m-0">Mostrar Todos</label>
|
||||
</div>
|
||||
|
||||
<hr className="dropdown-divider" />
|
||||
|
||||
<div className="dropdown-item d-flex align-items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="bancoCheck"
|
||||
className="me-2"
|
||||
checked={filters.banco}
|
||||
onChange={() => handleCheckboxChange('banco')}
|
||||
/>
|
||||
<label htmlFor="bancoCheck" className="m-0">Banco</label>
|
||||
</div>
|
||||
|
||||
<div className="dropdown-item d-flex align-items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="cajaCheck"
|
||||
className="me-2"
|
||||
checked={filters.caja}
|
||||
onChange={() => handleCheckboxChange('caja')}
|
||||
/>
|
||||
<label htmlFor="cajaCheck" className="m-0">Caja</label>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
GastosFilter.propTypes = {
|
||||
filters: PropTypes.object.isRequired,
|
||||
onChange: PropTypes.func.isRequired
|
||||
};
|
||||
|
||||
export default GastosFilter;
|
||||
117
src/components/Gastos/GastosPDF.jsx
Normal file
117
src/components/Gastos/GastosPDF.jsx
Normal file
@@ -0,0 +1,117 @@
|
||||
import { Document, Page, Text, View, StyleSheet, Font, Image } from '@react-pdf/renderer';
|
||||
import { CONSTANTS } from '../../util/constants';
|
||||
|
||||
Font.register({
|
||||
family: 'Open Sans',
|
||||
fonts: [{ src: '/fonts/OpenSans.ttf', fontWeight: 'normal' }]
|
||||
});
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
page: {
|
||||
padding: 25,
|
||||
fontSize: 12,
|
||||
fontFamily: 'Open Sans',
|
||||
backgroundColor: '#F8F9FA',
|
||||
},
|
||||
headerContainer: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
marginBottom: 25,
|
||||
justifyContent: 'left',
|
||||
},
|
||||
headerText: {
|
||||
flexDirection: 'column',
|
||||
marginLeft: 25,
|
||||
},
|
||||
logo: {
|
||||
width: 60,
|
||||
height: 60,
|
||||
},
|
||||
header: {
|
||||
fontSize: 26,
|
||||
fontWeight: 'bold',
|
||||
color: '#2C3E50',
|
||||
},
|
||||
subHeader: {
|
||||
fontSize: 12,
|
||||
marginTop: 5,
|
||||
color: '#34495E'
|
||||
},
|
||||
tableHeader: {
|
||||
flexDirection: 'row',
|
||||
backgroundColor: '#3E8F5A',
|
||||
fontWeight: 'bold',
|
||||
paddingVertical: 6,
|
||||
paddingHorizontal: 5,
|
||||
borderTopLeftRadius: 10,
|
||||
borderTopRightRadius: 10,
|
||||
},
|
||||
headerCell: {
|
||||
paddingHorizontal: 5,
|
||||
color: '#ffffff',
|
||||
fontWeight: 'bold',
|
||||
fontSize: 10,
|
||||
},
|
||||
row: {
|
||||
flexDirection: 'row',
|
||||
paddingVertical: 5,
|
||||
paddingHorizontal: 5,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: '#D5D8DC'
|
||||
},
|
||||
cell: {
|
||||
paddingHorizontal: 5,
|
||||
fontSize: 9,
|
||||
color: '#2C3E50'
|
||||
}
|
||||
});
|
||||
|
||||
const parseDate = (iso) => {
|
||||
if (!iso) return '';
|
||||
const [y, m, d] = iso.split('T')[0].split('-');
|
||||
return `${d}/${m}/${y}`;
|
||||
};
|
||||
|
||||
const getTypeLabel = (type) => type === CONSTANTS.PAYMENT_TYPE_BANK ? 'Banco' : 'Caja';
|
||||
|
||||
export const GastosPDF = ({ gastos }) => (
|
||||
<Document>
|
||||
<Page size="A4" orientation="landscape" style={styles.page}>
|
||||
<View style={styles.headerContainer}>
|
||||
<Image src="/images/logo.png" style={styles.logo} />
|
||||
<View style={styles.headerText}>
|
||||
<Text style={styles.header}>Listado de Gastos</Text>
|
||||
<Text style={styles.subHeader}>Asociación Huertos La Salud - Bellavista • Generado el {new Date().toLocaleDateString()} a las {new Date().toLocaleTimeString()}</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View style={styles.tableHeader}>
|
||||
<Text style={[styles.headerCell, { flex: 2 }]}>Fecha</Text>
|
||||
<Text style={[styles.headerCell, { flex: 4 }]}>Concepto</Text>
|
||||
<Text style={[styles.headerCell, { flex: 2 }]}>Importe</Text>
|
||||
<Text style={[styles.headerCell, { flex: 3 }]}>Proveedor</Text>
|
||||
<Text style={[styles.headerCell, { flex: 2 }]}>Factura</Text>
|
||||
<Text style={[styles.headerCell, { flex: 1 }]}>Tipo</Text>
|
||||
</View>
|
||||
|
||||
{gastos.map((gasto, idx) => (
|
||||
<View
|
||||
key={idx}
|
||||
style={[
|
||||
styles.row,
|
||||
{ backgroundColor: idx % 2 === 0 ? '#ECF0F1' : '#FDFEFE' },
|
||||
{ borderBottomLeftRadius: idx === gastos.length - 1 ? 10 : 0 },
|
||||
{ borderBottomRightRadius: idx === gastos.length - 1 ? 10 : 0 },
|
||||
]}
|
||||
>
|
||||
<Text style={[styles.cell, { flex: 2 }]}>{parseDate(gasto.created_at)}</Text>
|
||||
<Text style={[styles.cell, { flex: 4 }]}>{gasto.concept}</Text>
|
||||
<Text style={[styles.cell, { flex: 2 }]}>{gasto.amount.toFixed(2)} €</Text>
|
||||
<Text style={[styles.cell, { flex: 3 }]}>{gasto.supplier}</Text>
|
||||
<Text style={[styles.cell, { flex: 2 }]}>{gasto.invoice}</Text>
|
||||
<Text style={[styles.cell, { flex: 1 }]}>{getTypeLabel(gasto.type)}</Text>
|
||||
</View>
|
||||
))}
|
||||
</Page>
|
||||
</Document>
|
||||
);
|
||||
19
src/components/Header.jsx
Normal file
19
src/components/Header.jsx
Normal file
@@ -0,0 +1,19 @@
|
||||
import '../css/Header.css';
|
||||
import { Link } from 'react-router-dom';
|
||||
|
||||
const Header = () => {
|
||||
|
||||
return (
|
||||
<header className={`text-center bg-img`}>
|
||||
<div className="m-0 p-5 mask">
|
||||
<div className="d-flex flex-column justify-content-center align-items-center h-100">
|
||||
<Link to='/' className='text-decoration-none'>
|
||||
<h1 className='header-title m-0 text-white shadowed'>Asociación Huertos La Salud - Bellavista</h1>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
export default Header;
|
||||
283
src/components/Ingresos/IngresoCard.jsx
Normal file
283
src/components/Ingresos/IngresoCard.jsx
Normal file
@@ -0,0 +1,283 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import {
|
||||
Card, Badge, Button, Form, OverlayTrigger, Tooltip
|
||||
} from 'react-bootstrap';
|
||||
import PropTypes from 'prop-types';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import {
|
||||
faUser,
|
||||
faMoneyBillWave,
|
||||
faTrash,
|
||||
faEdit,
|
||||
faTimes,
|
||||
faEllipsisVertical
|
||||
} from '@fortawesome/free-solid-svg-icons';
|
||||
import { motion as _motion } from 'framer-motion';
|
||||
import AnimatedDropdown from '../../components/AnimatedDropdown';
|
||||
import { CONSTANTS } from '../../util/constants';
|
||||
import '../../css/IngresoCard.css';
|
||||
import { useTheme } from '../../hooks/useTheme';
|
||||
import { DateParser } from '../../util/parsers/dateParser';
|
||||
import { renderErrorAlert } from '../../util/alertHelpers';
|
||||
import { getNowAsLocalDatetime } from '../../util/date';
|
||||
import SpanishDateTimePicker from '../SpanishDateTimePicker';
|
||||
|
||||
const MotionCard = _motion.create(Card);
|
||||
|
||||
const getTypeLabel = (type) => type === CONSTANTS.PAYMENT_TYPE_BANK ? "Banco" : "Caja";
|
||||
const getFrequencyLabel = (freq) => freq === CONSTANTS.PAYMENT_FREQUENCY_BIYEARLY ? "Semestral" : "Anual";
|
||||
|
||||
const getTypeColor = (type, theme) => type === CONSTANTS.PAYMENT_TYPE_BANK ? "primary" : theme === "light" ? "dark" : "light";
|
||||
const getTypeTextColor = (type, theme) => type === CONSTANTS.PAYMENT_TYPE_BANK ? "light" : theme === "light" ? "light" : "dark";
|
||||
const getFreqColor = (freq) => freq === CONSTANTS.PAYMENT_FREQUENCY_BIYEARLY ? "warning" : "danger";
|
||||
const getFreqTextColor = (freq) => freq === CONSTANTS.PAYMENT_FREQUENCY_BIYEARLY ? "dark" : "light";
|
||||
|
||||
const getPFP = (tipo) => {
|
||||
const base = '/images/icons/';
|
||||
const map = {
|
||||
1: 'cash.svg',
|
||||
0: 'bank.svg'
|
||||
};
|
||||
return base + (map[tipo] || 'farmer.svg');
|
||||
};
|
||||
|
||||
const IngresoCard = ({
|
||||
income,
|
||||
isNew = false,
|
||||
onCreate,
|
||||
onUpdate,
|
||||
onDelete,
|
||||
onCancel,
|
||||
className = '',
|
||||
editable = true,
|
||||
error,
|
||||
onClearError,
|
||||
members = []
|
||||
}) => {
|
||||
const createMode = isNew;
|
||||
const [editMode, setEditMode] = useState(createMode);
|
||||
const { theme } = useTheme();
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
concept: income.concept || '',
|
||||
amount: income.amount || 0,
|
||||
type: income.type ?? CONSTANTS.PAYMENT_TYPE_CASH,
|
||||
frequency: income.frequency ?? CONSTANTS.PAYMENT_FREQUENCY_YEARLY,
|
||||
member_number: income.member_number,
|
||||
created_at: income.created_at?.slice(0, 16) || (isNew ? getNowAsLocalDatetime() : ''),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!editMode) {
|
||||
setFormData({
|
||||
concept: income.concept || '',
|
||||
amount: income.amount || 0,
|
||||
type: income.type ?? CONSTANTS.PAYMENT_TYPE_CASH,
|
||||
frequency: income.frequency ?? CONSTANTS.PAYMENT_FREQUENCY_YEARLY,
|
||||
display_name: income.display_name,
|
||||
member_number: income.member_number,
|
||||
created_at: income.created_at?.slice(0, 16) || (isNew ? getNowAsLocalDatetime() : ''),
|
||||
});
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [income, editMode]);
|
||||
|
||||
const handleChange = (field, value) =>
|
||||
setFormData(prev => ({ ...prev, [field]: value }));
|
||||
|
||||
const handleCancel = () => {
|
||||
if (onClearError) onClearError();
|
||||
if (isNew && typeof onCancel === 'function') return onCancel();
|
||||
setEditMode(false);
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
if (onClearError) onClearError();
|
||||
const newIncome = { ...income, ...formData };
|
||||
if (createMode && typeof onCreate === 'function') return onCreate(newIncome);
|
||||
if (typeof onUpdate === 'function') return onUpdate(newIncome, income.income_id);
|
||||
};
|
||||
|
||||
const handleDelete = () => typeof onDelete === 'function' && onDelete(income.income_id);
|
||||
|
||||
const uniqueMembers = Array.from(
|
||||
new Map(members.map(item => [item.member_number, item])).values()
|
||||
).sort((a, b) => a.member_number - b.member_number);
|
||||
|
||||
return (
|
||||
<MotionCard className={`ingreso-card shadow-sm rounded-4 border-0 h-100 ${className}`}>
|
||||
<Card.Header className="rounded-top-4 bg-light-green">
|
||||
<div className="d-flex justify-content-between align-items-center w-100">
|
||||
<div className="d-flex align-items-center">
|
||||
<img src={getPFP(formData.type)} width={36} alt="Ingreso" className='me-3' />
|
||||
<div className="d-flex flex-column">
|
||||
<span className="fw-bold">
|
||||
{editMode ? (
|
||||
<Form.Control
|
||||
className="themed-input"
|
||||
size="sm"
|
||||
value={formData.concept}
|
||||
onChange={(e) => handleChange('concept', e.target.value.toUpperCase())}
|
||||
/>
|
||||
) : formData.concept}
|
||||
</span>
|
||||
|
||||
<small>
|
||||
{editMode ? (
|
||||
<SpanishDateTimePicker
|
||||
selected={new Date(formData.created_at)}
|
||||
onChange={(date) =>
|
||||
handleChange('created_at', date.toISOString().slice(0, 16))
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
DateParser.isoToStringWithTime(formData.created_at)
|
||||
)}
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{editable && !createMode && !editMode && (
|
||||
<AnimatedDropdown
|
||||
className='ms-3'
|
||||
icon={<FontAwesomeIcon icon={faEllipsisVertical} className="fa-xl" />}
|
||||
>
|
||||
{({ closeDropdown }) => (
|
||||
<>
|
||||
<div className="dropdown-item d-flex align-items-center" onClick={() => { setEditMode(true); onClearError && onClearError(); closeDropdown(); }}>
|
||||
<FontAwesomeIcon icon={faEdit} className="me-2" />Editar
|
||||
</div>
|
||||
<div className="dropdown-item d-flex align-items-center text-danger" onClick={() => { handleDelete(); closeDropdown(); }}>
|
||||
<FontAwesomeIcon icon={faTrash} className="me-2" />Eliminar
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</AnimatedDropdown>
|
||||
)}
|
||||
</div>
|
||||
</Card.Header>
|
||||
|
||||
<Card.Body>
|
||||
{(editMode || createMode) && renderErrorAlert(error)}
|
||||
|
||||
<Card.Text className="mb-2">
|
||||
<FontAwesomeIcon icon={faUser} className="me-2" />
|
||||
<strong>Socio:</strong>{' '}
|
||||
{createMode ? (
|
||||
<Form.Select
|
||||
className="themed-input"
|
||||
size="sm"
|
||||
value={formData.member_number}
|
||||
onChange={(e) => handleChange('member_number', parseInt(e.target.value))}
|
||||
style={{ maxWidth: '300px', display: 'inline-block' }}
|
||||
>
|
||||
{uniqueMembers.map((m) => (
|
||||
<option key={m.member_number} value={m.member_number}>
|
||||
{`${m.display_name} (${m.member_number})`}
|
||||
</option>
|
||||
))}
|
||||
</Form.Select>
|
||||
) : editMode ? (
|
||||
<OverlayTrigger
|
||||
placement="top"
|
||||
overlay={<Tooltip>Este campo no se puede editar. Para cambiar el socio, elimina y vuelve a crear el ingreso.</Tooltip>}
|
||||
>
|
||||
<Form.Control
|
||||
className="themed-input"
|
||||
disabled
|
||||
size="sm"
|
||||
type="text"
|
||||
value={`${formData.display_name || 'Socio'} (${formData.member_number})`}
|
||||
style={{ maxWidth: '300px', display: 'inline-block' }}
|
||||
/>
|
||||
</OverlayTrigger>
|
||||
) : (
|
||||
formData.display_name ? (
|
||||
<>
|
||||
<OverlayTrigger
|
||||
placement="top"
|
||||
overlay={<Tooltip>{formData.display_name}</Tooltip>}
|
||||
>
|
||||
<span className="text-truncate d-inline-block" style={{ maxWidth: '200px', verticalAlign: 'middle' }}>
|
||||
{formData.display_name}
|
||||
</span>
|
||||
</OverlayTrigger>
|
||||
({formData.member_number})
|
||||
</>
|
||||
) : formData.member_number
|
||||
)}
|
||||
</Card.Text>
|
||||
|
||||
<Card.Text className="mb-2">
|
||||
<FontAwesomeIcon icon={faMoneyBillWave} className="me-2" />
|
||||
<strong>Importe:</strong>{' '}
|
||||
{editMode ? (
|
||||
<Form.Control
|
||||
className="themed-input"
|
||||
size="sm"
|
||||
type="number"
|
||||
step="0.01"
|
||||
value={formData.amount}
|
||||
onChange={(e) => handleChange('amount', parseFloat(e.target.value))}
|
||||
style={{ maxWidth: '150px', display: 'inline-block' }}
|
||||
/>
|
||||
) : `${formData.amount.toFixed(2)} €`}
|
||||
</Card.Text>
|
||||
|
||||
{editMode ? (
|
||||
<>
|
||||
<Form.Group className="mb-2">
|
||||
<Form.Label>Tipo de pago</Form.Label>
|
||||
<Form.Select
|
||||
className='themed-input'
|
||||
size="sm"
|
||||
value={formData.type}
|
||||
onChange={(e) => handleChange('type', parseInt(e.target.value))}
|
||||
>
|
||||
<option value={CONSTANTS.PAYMENT_TYPE_CASH}>Caja</option>
|
||||
<option value={CONSTANTS.PAYMENT_TYPE_BANK}>Banco</option>
|
||||
</Form.Select>
|
||||
</Form.Group>
|
||||
<Form.Group className="mb-3">
|
||||
<Form.Label>Frecuencia</Form.Label>
|
||||
<Form.Select
|
||||
className='themed-input'
|
||||
size="sm"
|
||||
value={formData.frequency}
|
||||
onChange={(e) => handleChange('frequency', parseInt(e.target.value))}
|
||||
>
|
||||
<option value={CONSTANTS.PAYMENT_FREQUENCY_YEARLY}>Anual</option>
|
||||
<option value={CONSTANTS.PAYMENT_FREQUENCY_BIYEARLY}>Semestral</option>
|
||||
</Form.Select>
|
||||
</Form.Group>
|
||||
<div className="d-flex justify-content-end gap-2">
|
||||
<Button variant="secondary" size="sm" onClick={handleCancel}><FontAwesomeIcon icon={faTimes} /> Cancelar</Button>
|
||||
<Button variant="primary" size="sm" onClick={handleSave}>Guardar</Button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="text-end">
|
||||
<Badge bg={getTypeColor(formData.type, theme)} text={getTypeTextColor(formData.type, theme)} className="me-1">{getTypeLabel(formData.type)}</Badge>
|
||||
<Badge bg={getFreqColor(formData.frequency)} text={getFreqTextColor(formData.frequency)}>{getFrequencyLabel(formData.frequency)}</Badge>
|
||||
</div>
|
||||
)}
|
||||
</Card.Body>
|
||||
</MotionCard>
|
||||
);
|
||||
};
|
||||
|
||||
IngresoCard.propTypes = {
|
||||
income: PropTypes.object.isRequired,
|
||||
isNew: PropTypes.bool,
|
||||
onCreate: PropTypes.func,
|
||||
onUpdate: PropTypes.func,
|
||||
onDelete: PropTypes.func,
|
||||
onCancel: PropTypes.func,
|
||||
className: PropTypes.string,
|
||||
editable: PropTypes.bool,
|
||||
error: PropTypes.string,
|
||||
onClearError: PropTypes.func,
|
||||
members: PropTypes.array
|
||||
};
|
||||
|
||||
export default IngresoCard;
|
||||
92
src/components/Ingresos/IngresosFilter.jsx
Normal file
92
src/components/Ingresos/IngresosFilter.jsx
Normal file
@@ -0,0 +1,92 @@
|
||||
import PropTypes from 'prop-types';
|
||||
|
||||
const IngresosFilter = ({ filters, onChange }) => {
|
||||
const handleCheckboxChange = (key) => {
|
||||
if (key === 'todos') {
|
||||
const newValue = !filters.todos;
|
||||
onChange({
|
||||
todos: newValue,
|
||||
banco: newValue,
|
||||
caja: newValue,
|
||||
semestral: newValue,
|
||||
anual: newValue
|
||||
});
|
||||
} else {
|
||||
const updated = { ...filters, [key]: !filters[key] };
|
||||
const allTrue = Object.entries(updated)
|
||||
.filter(([k]) => k !== 'todos')
|
||||
.every(([, v]) => v === true);
|
||||
|
||||
updated.todos = allTrue;
|
||||
onChange(updated);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="dropdown-item d-flex align-items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="todosCheck"
|
||||
className="me-2"
|
||||
checked={filters.todos}
|
||||
onChange={() => handleCheckboxChange('todos')}
|
||||
/>
|
||||
<label htmlFor="todosCheck" className="m-0">Mostrar Todos</label>
|
||||
</div>
|
||||
|
||||
<hr className="dropdown-divider" />
|
||||
|
||||
<div className="dropdown-item d-flex align-items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="bancoCheck"
|
||||
className="me-2"
|
||||
checked={filters.banco}
|
||||
onChange={() => handleCheckboxChange('banco')}
|
||||
/>
|
||||
<label htmlFor="bancoCheck" className="m-0">Banco</label>
|
||||
</div>
|
||||
|
||||
<div className="dropdown-item d-flex align-items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="cajaCheck"
|
||||
className="me-2"
|
||||
checked={filters.caja}
|
||||
onChange={() => handleCheckboxChange('caja')}
|
||||
/>
|
||||
<label htmlFor="cajaCheck" className="m-0">Caja</label>
|
||||
</div>
|
||||
|
||||
<div className="dropdown-item d-flex align-items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="semestralCheck"
|
||||
className="me-2"
|
||||
checked={filters.semestral}
|
||||
onChange={() => handleCheckboxChange('semestral')}
|
||||
/>
|
||||
<label htmlFor="semestralCheck" className="m-0">Semestral</label>
|
||||
</div>
|
||||
|
||||
<div className="dropdown-item d-flex align-items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="anualCheck"
|
||||
className="me-2"
|
||||
checked={filters.anual}
|
||||
onChange={() => handleCheckboxChange('anual')}
|
||||
/>
|
||||
<label htmlFor="anualCheck" className="m-0">Anual</label>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
IngresosFilter.propTypes = {
|
||||
filters: PropTypes.object.isRequired,
|
||||
onChange: PropTypes.func.isRequired
|
||||
};
|
||||
|
||||
export default IngresosFilter;
|
||||
118
src/components/Ingresos/IngresosPDF.jsx
Normal file
118
src/components/Ingresos/IngresosPDF.jsx
Normal file
@@ -0,0 +1,118 @@
|
||||
import { Document, Page, Text, View, StyleSheet, Font, Image } from '@react-pdf/renderer';
|
||||
import { CONSTANTS } from '../../util/constants';
|
||||
|
||||
Font.register({
|
||||
family: 'Open Sans',
|
||||
fonts: [{ src: '/fonts/OpenSans.ttf', fontWeight: 'normal' }]
|
||||
});
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
page: {
|
||||
padding: 25,
|
||||
fontSize: 12,
|
||||
fontFamily: 'Open Sans',
|
||||
backgroundColor: '#F8F9FA',
|
||||
},
|
||||
headerContainer: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
marginBottom: 25,
|
||||
justifyContent: 'left',
|
||||
},
|
||||
headerText: {
|
||||
flexDirection: 'column',
|
||||
marginLeft: 25,
|
||||
},
|
||||
logo: {
|
||||
width: 60,
|
||||
height: 60,
|
||||
},
|
||||
header: {
|
||||
fontSize: 26,
|
||||
fontWeight: 'bold',
|
||||
color: '#2C3E50',
|
||||
},
|
||||
subHeader: {
|
||||
fontSize: 12,
|
||||
marginTop: 5,
|
||||
color: '#34495E'
|
||||
},
|
||||
tableHeader: {
|
||||
flexDirection: 'row',
|
||||
backgroundColor: '#3E8F5A',
|
||||
fontWeight: 'bold',
|
||||
paddingVertical: 6,
|
||||
paddingHorizontal: 5,
|
||||
borderTopLeftRadius: 10,
|
||||
borderTopRightRadius: 10,
|
||||
},
|
||||
headerCell: {
|
||||
paddingHorizontal: 5,
|
||||
color: '#ffffff',
|
||||
fontWeight: 'bold',
|
||||
fontSize: 10,
|
||||
},
|
||||
row: {
|
||||
flexDirection: 'row',
|
||||
paddingVertical: 5,
|
||||
paddingHorizontal: 5,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: '#D5D8DC'
|
||||
},
|
||||
cell: {
|
||||
paddingHorizontal: 5,
|
||||
fontSize: 9,
|
||||
color: '#2C3E50'
|
||||
}
|
||||
});
|
||||
|
||||
const parseDate = (iso) => {
|
||||
if (!iso) return '';
|
||||
const [y, m, d] = iso.split('T')[0].split('-');
|
||||
return `${d}/${m}/${y}`;
|
||||
};
|
||||
|
||||
const getTypeLabel = (type) => type === CONSTANTS.PAYMENT_TYPE_BANK ? 'Banco' : 'Caja';
|
||||
const getFreqLabel = (freq) => freq === CONSTANTS.PAYMENT_FREQUENCY_BIYEARLY ? 'Semestral' : 'Anual';
|
||||
|
||||
export const IngresosPDF = ({ ingresos }) => (
|
||||
<Document>
|
||||
<Page size="A4" orientation="landscape" style={styles.page}>
|
||||
<View style={styles.headerContainer}>
|
||||
<Image src="/images/logo.png" style={styles.logo} />
|
||||
<View style={styles.headerText}>
|
||||
<Text style={styles.header}>Listado de ingresos</Text>
|
||||
<Text style={styles.subHeader}>Asociación Huertos La Salud - Bellavista • Generado el {new Date().toLocaleDateString()} a las {new Date().toLocaleTimeString()}</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View style={styles.tableHeader}>
|
||||
<Text style={[styles.headerCell, { flex: 1 }]}>Socio Nº</Text>
|
||||
<Text style={[styles.headerCell, { flex: 4 }]}>Concepto</Text>
|
||||
<Text style={[styles.headerCell, { flex: 1 }]}>Importe</Text>
|
||||
<Text style={[styles.headerCell, { flex: 1 }]}>Tipo</Text>
|
||||
<Text style={[styles.headerCell, { flex: 1 }]}>Frecuencia</Text>
|
||||
<Text style={[styles.headerCell, { flex: 2 }]}>Fecha</Text>
|
||||
</View>
|
||||
|
||||
{ingresos.map((ing, idx) => (
|
||||
<View
|
||||
key={idx}
|
||||
style={[
|
||||
styles.row,
|
||||
{ backgroundColor: idx % 2 === 0 ? '#ECF0F1' : '#FDFEFE' },
|
||||
{ borderBottomLeftRadius: idx === ingresos.length - 1 ? 10 : 0 },
|
||||
{ borderBottomRightRadius: idx === ingresos.length - 1 ? 10 : 0 },
|
||||
]}
|
||||
>
|
||||
<Text style={[styles.cell, { flex: 1 }]}>{ing.member_number}</Text>
|
||||
<Text style={[styles.cell, { flex: 3 }]}>{ing.concept}</Text>
|
||||
<Text style={[styles.cell, { flex: 1 }]}>{ing.amount.toFixed(2)} €</Text>
|
||||
<Text style={[styles.cell, { flex: 1 }]}>{getTypeLabel(ing.type)}</Text>
|
||||
<Text style={[styles.cell, { flex: 1 }]}>{getFreqLabel(ing.frequency)}</Text>
|
||||
<Text style={[styles.cell, { flex: 2 }]}>{parseDate(ing.created_at)}</Text>
|
||||
</View>
|
||||
))}
|
||||
</Page>
|
||||
</Document>
|
||||
);
|
||||
15
src/components/List.jsx
Normal file
15
src/components/List.jsx
Normal file
@@ -0,0 +1,15 @@
|
||||
import ListItem from "./ListItem";
|
||||
import {ListGroup} from 'react-bootstrap';
|
||||
import '../css/List.css';
|
||||
|
||||
const List = ({ datos, config }) => {
|
||||
return (
|
||||
<ListGroup className="gap-2">
|
||||
{datos.map((item, index) => (
|
||||
<ListItem key={index} item={item} config={config} index={index} />
|
||||
))}
|
||||
</ListGroup>
|
||||
);
|
||||
};
|
||||
|
||||
export default List;
|
||||
57
src/components/ListItem.jsx
Normal file
57
src/components/ListItem.jsx
Normal file
@@ -0,0 +1,57 @@
|
||||
import { motion as _motion } from "framer-motion";
|
||||
import { ListGroup } from "react-bootstrap";
|
||||
import '../css/ListItem.css';
|
||||
|
||||
const MotionListGroupItem = _motion.create(ListGroup.Item);
|
||||
|
||||
const ListItem = ({ item, config, index }) => {
|
||||
const {
|
||||
title,
|
||||
subtitle,
|
||||
numericField,
|
||||
pfp,
|
||||
showIndex,
|
||||
} = config;
|
||||
|
||||
return (
|
||||
<MotionListGroupItem
|
||||
className="custom-list-item d-flex justify-content-between rounded-4 align-items-center"
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
>
|
||||
<div className="d-flex align-items-center gap-3">
|
||||
{showIndex && (
|
||||
<div className="list-item-index">
|
||||
{index + 1}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{pfp && item[pfp] && (
|
||||
<img
|
||||
src={item[pfp]}
|
||||
alt="pfp"
|
||||
className="list-item-avatar"
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="d-flex flex-column">
|
||||
{title && item[title] && (
|
||||
<h5 className="fw-bold m-0">{item[title]}</h5>
|
||||
)}
|
||||
{subtitle && item[subtitle] && (
|
||||
<div className="subtitle m-0">{item[subtitle]}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{numericField && item[numericField] !== undefined && (
|
||||
<span className="badge bg-primary rounded-pill">
|
||||
{item[numericField]}
|
||||
</span>
|
||||
)}
|
||||
</MotionListGroupItem>
|
||||
);
|
||||
};
|
||||
|
||||
export default ListItem;
|
||||
10
src/components/LoadingIcon.jsx
Normal file
10
src/components/LoadingIcon.jsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { faSpinner } from '@fortawesome/free-solid-svg-icons';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
|
||||
const LoadingIcon = () => {
|
||||
return (
|
||||
<FontAwesomeIcon icon={faSpinner} className='fa-spin fa-lg' />
|
||||
);
|
||||
}
|
||||
|
||||
export default LoadingIcon;
|
||||
57
src/components/Mapa3D.jsx
Normal file
57
src/components/Mapa3D.jsx
Normal file
@@ -0,0 +1,57 @@
|
||||
// Mapa3D.jsx
|
||||
import { useEffect, useRef } from 'react';
|
||||
import maplibregl from 'maplibre-gl';
|
||||
import 'maplibre-gl/dist/maplibre-gl.css';
|
||||
|
||||
export default function Mapa3D() {
|
||||
const mapRef = useRef(null);
|
||||
|
||||
useEffect(() => {
|
||||
const map = new maplibregl.Map({
|
||||
container: mapRef.current,
|
||||
style: {
|
||||
version: 8,
|
||||
sources: {
|
||||
satellite: {
|
||||
type: 'raster',
|
||||
tiles: [
|
||||
'https://api.maptiler.com/maps/satellite/{z}/{x}/{y}@2x.jpg?key=Ie0BAF3X6PIp1aV260ar'
|
||||
],
|
||||
tileSize: 512,
|
||||
attribution: '© <a href="https://www.maptiler.com/">MapTiler</a>'
|
||||
}
|
||||
},
|
||||
layers: [
|
||||
{
|
||||
id: 'satellite',
|
||||
type: 'raster',
|
||||
source: 'satellite',
|
||||
minzoom: 0,
|
||||
maxzoom: 22
|
||||
}
|
||||
]
|
||||
},
|
||||
center: [-5.9648, 37.3282],
|
||||
zoom: 17,
|
||||
pitch: 30,
|
||||
bearing: -10,
|
||||
antialias: true,
|
||||
scrollZoom: false
|
||||
});
|
||||
|
||||
map.addControl(new maplibregl.NavigationControl());
|
||||
|
||||
new maplibregl.Marker()
|
||||
.setLngLat([-5.9648, 37.3282])
|
||||
.addTo(map);
|
||||
|
||||
return () => map.remove();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={mapRef}
|
||||
style={{ width: '100%', height: '60vh', borderRadius: '10px', overflow: 'hidden' }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
169
src/components/NavBar/NavBar.jsx
Normal file
169
src/components/NavBar/NavBar.jsx
Normal file
@@ -0,0 +1,169 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { useAuth } from "../../hooks/useAuth";
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import {
|
||||
faSignIn,
|
||||
faUser,
|
||||
faSignOut,
|
||||
faHouse,
|
||||
faList,
|
||||
faBullhorn,
|
||||
faFile
|
||||
} from '@fortawesome/free-solid-svg-icons';
|
||||
|
||||
import '../../css/NavBar.css';
|
||||
|
||||
import NavGestion from './NavGestion';
|
||||
import ThemeButton from '../ThemeButton.jsx';
|
||||
|
||||
import IfAuthenticated from '../Auth/IfAuthenticated.jsx';
|
||||
import IfNotAuthenticated from '../Auth/IfNotAuthenticated.jsx';
|
||||
import IfRole from '../Auth/IfRole.jsx';
|
||||
|
||||
import { Navbar, Nav, Container } from 'react-bootstrap';
|
||||
import AnimatedDropdown from '../AnimatedDropdown.jsx';
|
||||
|
||||
import { CONSTANTS } from '../../util/constants.js';
|
||||
|
||||
const NavBar = () => {
|
||||
const { user, logout } = useAuth();
|
||||
const [showingUserDropdown, setShowingUserDropdown] = useState(false);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [isLg, setIsLg] = useState(window.innerWidth >= 992);
|
||||
|
||||
useEffect(() => {
|
||||
const handleResize = () => {
|
||||
setIsLg(window.innerWidth >= 992 && window.innerWidth < 1200);
|
||||
};
|
||||
|
||||
handleResize(); // inicializar
|
||||
window.addEventListener('resize', handleResize);
|
||||
return () => window.removeEventListener('resize', handleResize);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const handleResize = () => {
|
||||
if (window.innerWidth >= 992) {
|
||||
setExpanded(false);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('resize', handleResize);
|
||||
return () => window.removeEventListener('resize', handleResize);
|
||||
});
|
||||
|
||||
|
||||
return (
|
||||
<Navbar expand="lg" sticky="top" expanded={expanded} onToggle={() => setExpanded(!expanded)}>
|
||||
<Container fluid>
|
||||
<Navbar.Toggle aria-controls="navbar" className="custom-toggler">
|
||||
<svg width="30" height="30" viewBox="0 0 30 30">
|
||||
<path
|
||||
d="M4 7h22M4 15h22M4 23h22"
|
||||
stroke="var(--navbar-link-color)"
|
||||
strokeWidth="3"
|
||||
strokeLinecap="round"
|
||||
strokeMiterlimit="10"
|
||||
/>
|
||||
</svg>
|
||||
</Navbar.Toggle>
|
||||
|
||||
<Navbar.Collapse id="main-navbar">
|
||||
<Nav className="me-auto gap-2">
|
||||
<Nav.Link
|
||||
as={Link}
|
||||
to="/"
|
||||
title="Inicio"
|
||||
href="/"
|
||||
className={`text-truncate ${expanded ? "mt-3" : ""}`}
|
||||
onClick={() => setExpanded(false)}
|
||||
>
|
||||
<FontAwesomeIcon icon={faHouse} className="me-2" />
|
||||
Inicio
|
||||
</Nav.Link>
|
||||
<Nav.Link
|
||||
as={Link}
|
||||
to="/lista-espera"
|
||||
title="Lista de espera"
|
||||
className={`text-truncate ${expanded ? "mt-3" : ""}`}
|
||||
onClick={() => setExpanded(false)}
|
||||
>
|
||||
<FontAwesomeIcon icon={faList} className="me-2" />
|
||||
Lista de espera
|
||||
</Nav.Link>
|
||||
|
||||
<IfAuthenticated>
|
||||
<Nav.Link
|
||||
as={Link}
|
||||
to="/anuncios"
|
||||
title="Anuncios"
|
||||
className={`text-truncate ${expanded ? "mt-3" : ""}`}
|
||||
onClick={() => setExpanded(false)}
|
||||
>
|
||||
<FontAwesomeIcon icon={faBullhorn} className="me-2" />Anuncios
|
||||
</Nav.Link>
|
||||
|
||||
<Nav.Link
|
||||
as={Link}
|
||||
to="/documentacion"
|
||||
title="Documentación"
|
||||
className={`text-truncate ${expanded ? "mt-3" : ""}`}
|
||||
onClick={() => setExpanded(false)}
|
||||
>
|
||||
<FontAwesomeIcon icon={faFile} className="me-2" />Documentación
|
||||
</Nav.Link>
|
||||
</IfAuthenticated>
|
||||
|
||||
<IfRole roles={[CONSTANTS.ROLE_ADMIN, CONSTANTS.ROLE_DEV]}>
|
||||
<NavGestion onNavigate={() => setExpanded(false)} externalExpanded={expanded} />
|
||||
</IfRole>
|
||||
<div className="d-lg-none mt-2 ms-2">
|
||||
<ThemeButton onlyIcon={isLg} />
|
||||
</div>
|
||||
</Nav>
|
||||
</Navbar.Collapse>
|
||||
|
||||
<div className="d-none d-lg-block me-3">
|
||||
<ThemeButton onlyIcon={isLg} />
|
||||
</div>
|
||||
|
||||
<Nav className="d-flex flex-md-row flex-column gap-2 ms-auto align-items-center">
|
||||
<IfAuthenticated>
|
||||
<AnimatedDropdown
|
||||
className='end-0 position-absolute'
|
||||
show={showingUserDropdown}
|
||||
onMouseEnter={() => setShowingUserDropdown(true)}
|
||||
onMouseLeave={() => setShowingUserDropdown(false)}
|
||||
onToggle={(isOpen) => setShowingUserDropdown(isOpen)}
|
||||
trigger={
|
||||
<Link className="nav-link dropdown-toggle fw-bold">
|
||||
@{user?.user_name}
|
||||
</Link>
|
||||
}
|
||||
>
|
||||
<Link to="/perfil" className="text-muted dropdown-item nav-link">
|
||||
<FontAwesomeIcon icon={faUser} className="me-2" />
|
||||
Mi perfil
|
||||
</Link>
|
||||
<hr className="dropdown-divider" />
|
||||
<Link to="#" className="dropdown-item nav-link" onClick={logout}>
|
||||
<FontAwesomeIcon icon={faSignOut} className="me-2" />
|
||||
Cerrar sesión
|
||||
</Link>
|
||||
</AnimatedDropdown>
|
||||
</IfAuthenticated>
|
||||
|
||||
<IfNotAuthenticated>
|
||||
<Nav.Link as={Link} to="/login" title="Iniciar sesión">
|
||||
<FontAwesomeIcon icon={faSignIn} className="me-2" />
|
||||
Iniciar sesión
|
||||
</Nav.Link>
|
||||
</IfNotAuthenticated>
|
||||
</Nav>
|
||||
</Container>
|
||||
</Navbar>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBar;
|
||||
67
src/components/NavBar/NavGestion.jsx
Normal file
67
src/components/NavBar/NavGestion.jsx
Normal file
@@ -0,0 +1,67 @@
|
||||
import { useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import AnimatedDropdown from '../../components/AnimatedDropdown';
|
||||
import AnimatedDropend from '../../components/AnimatedDropend';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import {
|
||||
faGear, faUsers, faMoneyBill, faWallet, faFileInvoice,
|
||||
faEnvelope,
|
||||
faBellConcierge,
|
||||
faPeopleGroup
|
||||
} from '@fortawesome/free-solid-svg-icons';
|
||||
import useRequestCount from '../../hooks/useRequestCount';
|
||||
|
||||
const NavGestion = ({ onNavigate, externalExpanded }) => {
|
||||
const [showing, setShowing] = useState(false);
|
||||
const count = useRequestCount();
|
||||
|
||||
return (
|
||||
<AnimatedDropdown
|
||||
show={showing}
|
||||
onMouseEnter={() => setShowing(true)}
|
||||
onMouseLeave={() => setShowing(false)}
|
||||
onToggle={(isOpen) => setShowing(isOpen)}
|
||||
trigger={
|
||||
<Link className={`nav-link dropdown-toggle ${externalExpanded ? "mt-3" : ""}`} role="button">
|
||||
<FontAwesomeIcon icon={faGear} className="me-2" />Gestión
|
||||
</Link>
|
||||
}
|
||||
>
|
||||
{/* Submenú lateral: Asociación */}
|
||||
<AnimatedDropend
|
||||
trigger={
|
||||
<Link className="nav-link dropdown-toggle" role='button'>
|
||||
<FontAwesomeIcon icon={faPeopleGroup} className="me-2" />Asociación
|
||||
</Link>
|
||||
}
|
||||
>
|
||||
<Link to="/gestion/socios" className="dropdown-item nav-link" onClick={onNavigate}>
|
||||
<FontAwesomeIcon icon={faUsers} className="me-2" />Socios
|
||||
</Link>
|
||||
<Link to="/gestion/ingresos" className="dropdown-item nav-link" onClick={onNavigate}>
|
||||
<FontAwesomeIcon icon={faMoneyBill} className="me-2" />Ingresos
|
||||
</Link>
|
||||
<Link to="/gestion/gastos" className="dropdown-item nav-link" onClick={onNavigate}>
|
||||
<FontAwesomeIcon icon={faWallet} className="me-2" />Gastos
|
||||
</Link>
|
||||
<Link to="/gestion/balance" className="dropdown-item nav-link" onClick={onNavigate}>
|
||||
<FontAwesomeIcon icon={faFileInvoice} className="me-2" />Balance
|
||||
</Link>
|
||||
</AnimatedDropend>
|
||||
|
||||
<Link to="/gestion/solicitudes" className="dropdown-item nav-link" onClick={onNavigate}>
|
||||
<FontAwesomeIcon icon={faBellConcierge} />
|
||||
<span className="icon-with-badge">
|
||||
{count > 0 && <span className="icon-badge">{count}</span>}
|
||||
</span>
|
||||
Solicitudes
|
||||
</Link>
|
||||
|
||||
<Link to="/correo" className="dropdown-item nav-link" onClick={onNavigate}>
|
||||
<FontAwesomeIcon icon={faEnvelope} className="me-2" />Correo
|
||||
</Link>
|
||||
</AnimatedDropdown>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavGestion;
|
||||
69
src/components/NotificationModal.jsx
Normal file
69
src/components/NotificationModal.jsx
Normal file
@@ -0,0 +1,69 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Modal, Button } from 'react-bootstrap';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import {
|
||||
faCircleCheck,
|
||||
faCircleXmark,
|
||||
faCircleExclamation,
|
||||
faCircleInfo
|
||||
} from '@fortawesome/free-solid-svg-icons';
|
||||
|
||||
const iconMap = {
|
||||
success: faCircleCheck,
|
||||
danger: faCircleXmark,
|
||||
warning: faCircleExclamation,
|
||||
info: faCircleInfo
|
||||
};
|
||||
|
||||
const NotificationModal = ({
|
||||
show,
|
||||
onClose,
|
||||
title,
|
||||
message,
|
||||
variant = "info",
|
||||
buttons = [{ label: "Aceptar", variant: "primary", onClick: onClose }]
|
||||
}) => {
|
||||
return (
|
||||
<Modal show={show} onHide={onClose} centered>
|
||||
<Modal.Header closeButton className={`bg-${variant} ${variant === 'info' ? 'text-dark' : 'text-white'}`}>
|
||||
<Modal.Title>
|
||||
<FontAwesomeIcon icon={iconMap[variant] || faCircleInfo} className="me-2" />
|
||||
{title}
|
||||
</Modal.Title>
|
||||
</Modal.Header>
|
||||
|
||||
<Modal.Body>
|
||||
<p className="mb-0">{message}</p>
|
||||
</Modal.Body>
|
||||
|
||||
<Modal.Footer>
|
||||
{buttons.map((btn, index) => (
|
||||
<Button
|
||||
key={index}
|
||||
variant={btn.variant || "primary"}
|
||||
onClick={btn.onClick || onClose}
|
||||
>
|
||||
{btn.label}
|
||||
</Button>
|
||||
))}
|
||||
</Modal.Footer>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
NotificationModal.propTypes = {
|
||||
show: PropTypes.bool.isRequired,
|
||||
onClose: PropTypes.func.isRequired,
|
||||
title: PropTypes.string.isRequired,
|
||||
message: PropTypes.string.isRequired,
|
||||
variant: PropTypes.oneOf(['success', 'danger', 'warning', 'info']),
|
||||
buttons: PropTypes.arrayOf(
|
||||
PropTypes.shape({
|
||||
label: PropTypes.string.isRequired,
|
||||
variant: PropTypes.string,
|
||||
onClick: PropTypes.func
|
||||
})
|
||||
)
|
||||
};
|
||||
|
||||
export default NotificationModal;
|
||||
22
src/components/PDFModal.jsx
Normal file
22
src/components/PDFModal.jsx
Normal file
@@ -0,0 +1,22 @@
|
||||
import { faXmark } from "@fortawesome/free-solid-svg-icons";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { Modal, Button } from "react-bootstrap";
|
||||
import { PDFViewer } from "@react-pdf/renderer";
|
||||
|
||||
const PDFModal = ({ show, onClose, title, children }) => (
|
||||
<Modal show={show} onHide={onClose} size="xl" centered>
|
||||
<Modal.Header className='justify-content-between'>
|
||||
<Modal.Title>{title}</Modal.Title>
|
||||
<Button variant='transparent' onClick={onClose}>
|
||||
<FontAwesomeIcon icon={faXmark} className='close-button fa-xl' />
|
||||
</Button>
|
||||
</Modal.Header>
|
||||
<Modal.Body className="rounded-bottom-4 p-0" style={{ height: '80vh' }}>
|
||||
<PDFViewer width="100%" height="100%">
|
||||
{children}
|
||||
</PDFViewer>
|
||||
</Modal.Body>
|
||||
</Modal>
|
||||
);
|
||||
|
||||
export default PDFModal;
|
||||
24
src/components/PaginatedCardGrid.jsx
Normal file
24
src/components/PaginatedCardGrid.jsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import LoadingIcon from './LoadingIcon';
|
||||
|
||||
const PaginatedCardGrid = ({
|
||||
items = [],
|
||||
renderCard,
|
||||
creatingItem = null,
|
||||
renderCreatingCard = null,
|
||||
loaderRef,
|
||||
loading = false
|
||||
}) => {
|
||||
return (
|
||||
<div className="cards-grid">
|
||||
{creatingItem && renderCreatingCard && renderCreatingCard()}
|
||||
|
||||
{items.map((item, i) => renderCard(item, i))}
|
||||
|
||||
<div ref={loaderRef} className="loading-trigger d-flex justify-content-center align-items-center">
|
||||
{loading && <LoadingIcon />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default PaginatedCardGrid;
|
||||
43
src/components/SearchToolbar.jsx
Normal file
43
src/components/SearchToolbar.jsx
Normal file
@@ -0,0 +1,43 @@
|
||||
import { faFilter, faFilePdf, faPlus } from '@fortawesome/free-solid-svg-icons';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import AnimatedDropdown from './AnimatedDropdown';
|
||||
import Button from 'react-bootstrap/Button';
|
||||
import { CONSTANTS } from '../util/constants';
|
||||
import IfRole from './Auth/IfRole';
|
||||
|
||||
const SearchToolbar = ({ searchTerm, onSearchChange, filtersComponent, onCreate, onPDF }) => (
|
||||
<div className="sticky-toolbar search-toolbar-wrapper">
|
||||
<div className="search-toolbar">
|
||||
<input
|
||||
type="text"
|
||||
className="search-input"
|
||||
placeholder="Buscar..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => onSearchChange(e.target.value)}
|
||||
/>
|
||||
<div className="toolbar-buttons">
|
||||
{filtersComponent && (
|
||||
<AnimatedDropdown variant="transparent" icon={<FontAwesomeIcon icon={faFilter} className='fa-md' />}>
|
||||
{filtersComponent}
|
||||
</AnimatedDropdown>
|
||||
)}
|
||||
{onPDF && (
|
||||
<IfRole roles={[CONSTANTS.ROLE_ADMIN, CONSTANTS.ROLE_DEV]}>
|
||||
<Button variant="transparent" onClick={onPDF}>
|
||||
<FontAwesomeIcon icon={faFilePdf} className='fa-md' />
|
||||
</Button>
|
||||
</IfRole>
|
||||
)}
|
||||
{onCreate && (
|
||||
<IfRole roles={[CONSTANTS.ROLE_ADMIN, CONSTANTS.ROLE_DEV]}>
|
||||
<Button variant="transparent" onClick={onCreate}>
|
||||
<FontAwesomeIcon icon={faPlus} className='fa-md' />
|
||||
</Button>
|
||||
</IfRole>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
export default SearchToolbar;
|
||||
364
src/components/Socios/SocioCard.jsx
Normal file
364
src/components/Socios/SocioCard.jsx
Normal file
@@ -0,0 +1,364 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import {
|
||||
Card, ListGroup, Badge, Button, Form,
|
||||
Tooltip, OverlayTrigger
|
||||
} from 'react-bootstrap';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import {
|
||||
faIdCard, faUser, faSunPlantWilt, faPhone, faClipboard, faAt,
|
||||
faEllipsisVertical, faEdit, faTrash, faMoneyBill,
|
||||
faCheck,
|
||||
faXmark,
|
||||
faCalendar,
|
||||
faKey
|
||||
} from '@fortawesome/free-solid-svg-icons';
|
||||
import { motion as _motion } from 'framer-motion';
|
||||
import PropTypes from 'prop-types';
|
||||
import AnimatedDropdown from '../../components/AnimatedDropdown';
|
||||
import '../../css/SocioCard.css';
|
||||
import TipoSocioDropdown from './TipoSocioDropdown';
|
||||
import { getNowAsLocalDatetime } from '../../util/date';
|
||||
import { generateSecurePassword } from '../../util/passwordGenerator';
|
||||
import { DateParser } from '../../util/parsers/dateParser';
|
||||
import { renderErrorAlert } from '../../util/alertHelpers';
|
||||
import { useDataContext } from "../../hooks/useDataContext";
|
||||
import SpanishDateTimePicker from '../SpanishDateTimePicker';
|
||||
|
||||
const renderDateField = (label, icon, dateValue, editMode, fieldKey, handleChange) => {
|
||||
if (!editMode && !dateValue) return null;
|
||||
|
||||
return (
|
||||
<ListGroup.Item className="d-flex justify-content-between align-items-center">
|
||||
<span><FontAwesomeIcon icon={icon} className="me-2" />{label}</span>
|
||||
{editMode ? (
|
||||
<SpanishDateTimePicker
|
||||
selected={dateValue ? new Date(dateValue) : null}
|
||||
onChange={(date) =>
|
||||
date ? handleChange(fieldKey, date.toISOString().slice(0, 16)) : handleChange(fieldKey, null)
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<strong>{DateParser.isoToStringWithTime(dateValue)}</strong>
|
||||
)}
|
||||
</ListGroup.Item>
|
||||
);
|
||||
};
|
||||
|
||||
const getFechas = (formData, editMode, handleChange) => {
|
||||
const { created_at, assigned_at, deactivated_at } = formData;
|
||||
|
||||
// Si no hay fechas y no está en modo edición, no muestres nada
|
||||
if (!editMode && !created_at && !assigned_at && !deactivated_at) return null;
|
||||
|
||||
return (
|
||||
<ListGroup className="mt-2 border-1 rounded-3 shadow-sm">
|
||||
{renderDateField("ALTA", faCalendar, created_at, editMode, "created_at", handleChange)}
|
||||
{renderDateField("ENTREGA", faCalendar, assigned_at, editMode, "assigned_at", handleChange)}
|
||||
{renderDateField("BAJA", faCalendar, deactivated_at, editMode, "deactivated_at", handleChange)}
|
||||
</ListGroup>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
const getBadgeColor = (estado) => estado === 1 ? 'success' : 'danger';
|
||||
const getHeaderColor = (estado) => estado === 1 ? 'bg-light-green' : 'bg-light-red';
|
||||
const getEstado = (estado) =>
|
||||
estado === 1 ? (
|
||||
<>
|
||||
<FontAwesomeIcon icon={faCheck} className="me-2" />
|
||||
ACTIVO
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<FontAwesomeIcon icon={faXmark} className="me-2" />
|
||||
INACTIVO
|
||||
</>
|
||||
);
|
||||
|
||||
const parseNull = (attr) => attr === null || attr === '' ? 'NO' : attr;
|
||||
const getPFP = (tipo) => {
|
||||
const base = '/images/icons/';
|
||||
const map = {
|
||||
1: 'farmer.svg',
|
||||
2: 'green_house.svg',
|
||||
0: 'list.svg',
|
||||
3: 'join.svg',
|
||||
4: 'subvencion4.svg',
|
||||
5: 'programmer.svg'
|
||||
};
|
||||
return base + (map[tipo] || 'farmer.svg');
|
||||
};
|
||||
|
||||
const MotionCard = _motion.create(Card);
|
||||
|
||||
const SocioCard = ({ socio, isNew = false, onCreate, onUpdate, onDelete, onCancel, onViewIncomes, error, onClearError, positionIfWaitlist }) => {
|
||||
const createMode = isNew;
|
||||
const [editMode, setEditMode] = useState(isNew);
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [latestNumber, setLatestNumber] = useState(null);
|
||||
const { getData } = useDataContext();
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
display_name: socio.display_name,
|
||||
user_name: socio.user_name,
|
||||
email: socio.email || '',
|
||||
dni: socio.dni,
|
||||
phone: socio.phone,
|
||||
member_number: socio.member_number || latestNumber,
|
||||
plot_number: socio.plot_number,
|
||||
notes: socio.notes || '',
|
||||
status: socio.status,
|
||||
type: socio.type,
|
||||
created_at: socio.created_at?.slice(0, 16) || (isNew ? getNowAsLocalDatetime() : ''),
|
||||
assigned_at: socio.assigned_at?.slice(0, 16) || undefined,
|
||||
deactivated_at: socio.deactivated_at?.slice(0, 16) || undefined,
|
||||
global_role: 0,
|
||||
password: createMode && !editMode ? generateSecurePassword() : null,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!editMode) {
|
||||
setFormData({
|
||||
display_name: socio.display_name,
|
||||
user_name: socio.user_name,
|
||||
email: socio.email || '',
|
||||
dni: socio.dni,
|
||||
phone: socio.phone,
|
||||
member_number: socio.member_number,
|
||||
plot_number: socio.plot_number,
|
||||
notes: socio.notes || '',
|
||||
status: socio.status,
|
||||
type: socio.type,
|
||||
created_at: socio.created_at?.slice(0, 16) || (isNew ? getNowAsLocalDatetime() : ''),
|
||||
assigned_at: socio.assigned_at?.slice(0, 16) || undefined,
|
||||
deactivated_at: socio.deactivated_at?.slice(0, 16) || undefined,
|
||||
global_role: 0,
|
||||
password: createMode ? generateSecurePassword() : ''
|
||||
});
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [socio, editMode]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchLastNumber = async () => {
|
||||
try {
|
||||
if (!(createMode || editMode)) return;
|
||||
|
||||
const { data, error } = await getData("https://api.huertosbellavista.es/v1/members/latest-number");
|
||||
if (error) throw new Error(error);
|
||||
|
||||
const nuevoNumero = data.lastMemberNumber + 1;
|
||||
setLatestNumber(nuevoNumero);
|
||||
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
member_number: prev.member_number || nuevoNumero
|
||||
}));
|
||||
} catch (err) {
|
||||
console.error("Error al obtener el número de socio:", err);
|
||||
}
|
||||
};
|
||||
|
||||
fetchLastNumber();
|
||||
}, [createMode, editMode, getData]);
|
||||
|
||||
const handleEdit = () => {
|
||||
if (onClearError) onClearError();
|
||||
setEditMode(true);
|
||||
};
|
||||
|
||||
const handleDelete = () => typeof onDelete === "function" && onDelete(socio.user_id);
|
||||
|
||||
const handleCancel = () => {
|
||||
if (onClearError) onClearError();
|
||||
if (isNew && typeof onCancel === 'function') return onCancel();
|
||||
setEditMode(false);
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
if (onClearError) onClearError();
|
||||
const newSocio = { ...socio, ...formData };
|
||||
if (createMode && typeof onCreate === 'function') return onCreate(newSocio);
|
||||
if (typeof onUpdate === 'function') return onUpdate(newSocio, socio.user_id);
|
||||
};
|
||||
|
||||
const handleChange = (field, value) => {
|
||||
if (["member_number"].includes(field)) {
|
||||
value = value === "" ? latestNumber : parseInt(value);
|
||||
}
|
||||
if (field === "display_name") {
|
||||
value = value.toUpperCase();
|
||||
}
|
||||
if (field === "dni") {
|
||||
value = value.toUpperCase();
|
||||
}
|
||||
setFormData(prev => ({ ...prev, [field]: value }));
|
||||
};
|
||||
|
||||
const handleViewIncomes = () => {
|
||||
onViewIncomes(socio.user_id);
|
||||
}
|
||||
|
||||
return (
|
||||
<MotionCard className="socio-card shadow-sm rounded-4 h-100">
|
||||
<Card.Header className={`d-flex align-items-center rounded-4 rounded-bottom-0 justify-content-between ${getHeaderColor(formData.status)}`}>
|
||||
<div className="d-flex align-items-center p-1 m-0">
|
||||
{editMode ? (
|
||||
<TipoSocioDropdown value={formData.type} onChange={(val) => handleChange('type', val)} />
|
||||
) : (
|
||||
positionIfWaitlist && socio.type === 0 ? (
|
||||
<OverlayTrigger
|
||||
placement="top"
|
||||
overlay={
|
||||
<Tooltip>
|
||||
Nº <strong>{positionIfWaitlist}</strong> en la lista de espera
|
||||
</Tooltip>
|
||||
}>
|
||||
<span className="me-3">
|
||||
<img src={getPFP(formData.type)} width="36" className="rounded" alt="PFP" />
|
||||
</span>
|
||||
</OverlayTrigger>
|
||||
) : (
|
||||
<img src={getPFP(formData.type)} width="36" className="rounded me-3" alt="PFP" />
|
||||
)
|
||||
)}
|
||||
<div className='d-flex flex-column gap-1'>
|
||||
<Card.Title className="m-0">
|
||||
{editMode ? (
|
||||
<Form.Control className="themed-input" size="sm" value={formData.display_name} onChange={(e) => handleChange('display_name', e.target.value)} style={{ maxWidth: '220px' }} />
|
||||
) : formData.display_name}
|
||||
</Card.Title>
|
||||
{editMode ? (
|
||||
<Form.Select className="themed-input" size="sm" value={formData.status} onChange={(e) => handleChange('status', parseInt(e.target.value))} style={{ maxWidth: '8rem' }}>
|
||||
<option value={1}>ACTIVO</option>
|
||||
<option value={0}>INACTIVO</option>
|
||||
</Form.Select>
|
||||
) : (
|
||||
<Badge style={{ width: 'fit-content' }} bg={getBadgeColor(formData.status)}>{getEstado(formData.status)}</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!createMode && !editMode && (
|
||||
<AnimatedDropdown
|
||||
className='end-0'
|
||||
buttonStyle='card-button'
|
||||
icon={<FontAwesomeIcon icon={faEllipsisVertical} className="fa-xl" />}>
|
||||
{({ closeDropdown }) => (
|
||||
<>
|
||||
<div className="dropdown-item d-flex align-items-center" onClick={() => { handleEdit(); closeDropdown(); }}>
|
||||
<FontAwesomeIcon icon={faEdit} className="me-2" />Editar
|
||||
</div>
|
||||
<div className="dropdown-item d-flex align-items-center" onClick={() => { handleViewIncomes(); closeDropdown(); }}>
|
||||
<FontAwesomeIcon icon={faMoneyBill} className="me-2" />Ver ingresos
|
||||
</div>
|
||||
<hr className="dropdown-divider" />
|
||||
<div className="dropdown-item d-flex align-items-center text-danger" onClick={() => { handleDelete(); closeDropdown(); }}>
|
||||
<FontAwesomeIcon icon={faTrash} className="me-2" />Eliminar
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</AnimatedDropdown>
|
||||
)}
|
||||
</Card.Header>
|
||||
|
||||
<Card.Body>
|
||||
{(editMode || createMode) && renderErrorAlert(error)}
|
||||
|
||||
<ListGroup className="mt-2 border-1 rounded-3 shadow-sm">
|
||||
{[{
|
||||
label: 'DNI', clazz: '', icon: faIdCard, value: formData.dni, field: 'dni', type: 'text', maxWidth: '180px'
|
||||
}, {
|
||||
label: 'SOCIO Nº', clazz: '', icon: faUser, value: formData.member_number || latestNumber, field: 'member_number', type: 'number', maxWidth: '100px'
|
||||
}, {
|
||||
label: 'HUERTO Nº', clazz: '', icon: faSunPlantWilt, value: formData.plot_number, field: 'plot_number', type: 'number', maxWidth: '100px'
|
||||
}, {
|
||||
label: 'TLF.', clazz: '', icon: faPhone, value: formData.phone, field: 'phone', type: 'number', maxWidth: '200px'
|
||||
}, {
|
||||
label: 'EMAIL', clazz: 'text-truncate', icon: faAt, value: formData.email, field: 'email', type: 'text', maxWidth: '250px'
|
||||
}].map(({ label, clazz, icon, value, field, type, maxWidth }) => (
|
||||
<ListGroup.Item key={field} className="d-flex justify-content-between align-items-center">
|
||||
<span><FontAwesomeIcon icon={icon} className="me-2" />{label}</span>
|
||||
{editMode ? (
|
||||
<Form.Control className="themed-input" size="sm" type={type} value={value} onChange={(e) => handleChange(field, e.target.value)} style={{ maxWidth }} />
|
||||
) : (
|
||||
<strong className={clazz}>{parseNull(value)}</strong>
|
||||
)}
|
||||
</ListGroup.Item>
|
||||
))}
|
||||
{editMode && (
|
||||
<ListGroup.Item className="d-flex justify-content-between align-items-center">
|
||||
<span><FontAwesomeIcon icon={faKey} className="me-2" />CONTRASEÑA</span>
|
||||
<div className="d-flex align-items-center gap-2" style={{ maxWidth: 'fit-content' }}>
|
||||
<Form.Control
|
||||
className="themed-input"
|
||||
size="sm"
|
||||
type={showPassword ? "text" : "password"}
|
||||
value={formData.password}
|
||||
onChange={(e) => handleChange('password', e.target.value)}
|
||||
style={{ maxWidth: '200px' }}
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline-secondary"
|
||||
onClick={() => setShowPassword(prev => !prev)}
|
||||
>
|
||||
{showPassword ? "Ocultar" : "Mostrar"}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline-secondary"
|
||||
onClick={() => handleChange('password', generateSecurePassword())}
|
||||
>
|
||||
Generar
|
||||
</Button>
|
||||
</div>
|
||||
</ListGroup.Item>
|
||||
)}
|
||||
|
||||
</ListGroup>
|
||||
|
||||
{getFechas(formData, editMode, handleChange)}
|
||||
|
||||
<Card className="mt-2 border-1 rounded-3 notas-card">
|
||||
<Card.Body>
|
||||
<Card.Subtitle className="mb-2">
|
||||
{editMode ? (
|
||||
<><FontAwesomeIcon icon={faClipboard} className="me-2" />NOTAS (máx. 256)</>
|
||||
) : (
|
||||
<><FontAwesomeIcon icon={faClipboard} className="me-2" />NOTAS</>
|
||||
)}
|
||||
</Card.Subtitle>
|
||||
{editMode ? (
|
||||
<Form.Control className="themed-input" as="textarea" rows={3} value={formData.notes} onChange={(e) => handleChange('notes', e.target.value)} />
|
||||
) : (
|
||||
<Card.Text>{parseNull(formData.notes)}</Card.Text>
|
||||
)}
|
||||
</Card.Body>
|
||||
</Card>
|
||||
|
||||
{editMode && (
|
||||
<div className="d-flex justify-content-end gap-2 mt-3">
|
||||
<Button variant="danger" size="sm" onClick={handleCancel}>Cancelar</Button>
|
||||
<Button variant="success" size="sm" onClick={handleSave}>Guardar</Button>
|
||||
</div>
|
||||
)}
|
||||
</Card.Body>
|
||||
</MotionCard>
|
||||
);
|
||||
};
|
||||
|
||||
SocioCard.propTypes = {
|
||||
socio: PropTypes.object.isRequired,
|
||||
isNew: PropTypes.bool,
|
||||
onCancel: PropTypes.func,
|
||||
onCreate: PropTypes.func,
|
||||
onUpdate: PropTypes.func,
|
||||
onDelete: PropTypes.func,
|
||||
onViewIncomes: PropTypes.func,
|
||||
error: PropTypes.string,
|
||||
onClearError: PropTypes.func,
|
||||
positionIfWaitlist: PropTypes.number
|
||||
};
|
||||
|
||||
export default SocioCard;
|
||||
104
src/components/Socios/SociosFilter.jsx
Normal file
104
src/components/Socios/SociosFilter.jsx
Normal file
@@ -0,0 +1,104 @@
|
||||
import PropTypes from 'prop-types';
|
||||
|
||||
const SociosFilter = ({ filters, onChange }) => {
|
||||
const handleCheckboxChange = (key) => {
|
||||
if (key === 'todos') {
|
||||
const newValue = !filters.todos;
|
||||
onChange({
|
||||
todos: newValue,
|
||||
listaEspera: newValue,
|
||||
invernadero: newValue,
|
||||
inactivos: newValue,
|
||||
colaboradores: newValue,
|
||||
hortelanos: newValue
|
||||
});
|
||||
} else {
|
||||
const updated = { ...filters, [key]: !filters[key] };
|
||||
const allTrue = Object.entries(updated)
|
||||
.filter(([k]) => k !== 'todos')
|
||||
.every(([, v]) => v === true);
|
||||
|
||||
updated.todos = allTrue;
|
||||
onChange(updated);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="dropdown-item d-flex align-items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="mostrarTodosCheck"
|
||||
className="me-2"
|
||||
checked={filters.todos}
|
||||
onChange={() => handleCheckboxChange('todos')}
|
||||
/>
|
||||
<label htmlFor="mostrarTodosCheck" className="m-0">Mostrar Todos</label>
|
||||
</div>
|
||||
|
||||
<hr className="dropdown-divider" />
|
||||
|
||||
<div className="dropdown-item d-flex align-items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="esperaCheck"
|
||||
className="me-2"
|
||||
checked={filters.listaEspera}
|
||||
onChange={() => handleCheckboxChange('listaEspera')}
|
||||
/>
|
||||
<label htmlFor="esperaCheck" className="m-0">Lista de Espera</label>
|
||||
</div>
|
||||
|
||||
<div className="dropdown-item d-flex align-items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="invernaderosCheck"
|
||||
className="me-2"
|
||||
checked={filters.invernadero}
|
||||
onChange={() => handleCheckboxChange('invernadero')}
|
||||
/>
|
||||
<label htmlFor="invernaderosCheck" className="m-0">Invernadero</label>
|
||||
</div>
|
||||
|
||||
<div className="dropdown-item d-flex align-items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="inactivosCheck"
|
||||
className="me-2"
|
||||
checked={filters.inactivos}
|
||||
onChange={() => handleCheckboxChange('inactivos')}
|
||||
/>
|
||||
<label htmlFor="inactivosCheck" className="m-0">Inactivos</label>
|
||||
</div>
|
||||
|
||||
<div className="dropdown-item d-flex align-items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="colaboradoresCheck"
|
||||
className="me-2"
|
||||
checked={filters.colaboradores}
|
||||
onChange={() => handleCheckboxChange('colaboradores')}
|
||||
/>
|
||||
<label htmlFor="colaboradoresCheck" className="m-0">Colaboradores</label>
|
||||
</div>
|
||||
|
||||
<div className="dropdown-item d-flex align-items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="hortelanosCheck"
|
||||
className="me-2"
|
||||
checked={filters.hortelanos}
|
||||
onChange={() => handleCheckboxChange('hortelanos')}
|
||||
/>
|
||||
<label htmlFor="hortelanosCheck" className="m-0">Hortelanos</label>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
SociosFilter.propTypes = {
|
||||
filters: PropTypes.object.isRequired,
|
||||
onChange: PropTypes.func.isRequired
|
||||
};
|
||||
|
||||
export default SociosFilter;
|
||||
132
src/components/Socios/SociosPDF.jsx
Normal file
132
src/components/Socios/SociosPDF.jsx
Normal file
@@ -0,0 +1,132 @@
|
||||
import React from 'react';
|
||||
import { Document, Page, Text, View, StyleSheet, Font, Image } from '@react-pdf/renderer';
|
||||
|
||||
Font.register({
|
||||
family: 'Open Sans',
|
||||
fonts: [{ src: '/fonts/OpenSans.ttf', fontWeight: 'normal' }]
|
||||
});
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
page: {
|
||||
padding: 25,
|
||||
fontSize: 14,
|
||||
fontFamily: 'Open Sans',
|
||||
backgroundColor: '#F8F9FA',
|
||||
},
|
||||
headerContainer: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
marginBottom: 25,
|
||||
justifyContent: 'left',
|
||||
},
|
||||
headerText: {
|
||||
flexDirection: 'column',
|
||||
justifyContent: 'left',
|
||||
alignItems: 'center',
|
||||
marginLeft: 25,
|
||||
},
|
||||
logo: {
|
||||
width: 60,
|
||||
height: 60,
|
||||
},
|
||||
header: {
|
||||
fontSize: 28,
|
||||
fontWeight: 'bold',
|
||||
color: '#2C3E50',
|
||||
letterSpacing: 1.5,
|
||||
},
|
||||
subHeader: {
|
||||
fontSize: 14,
|
||||
marginTop: 5,
|
||||
color: '#34495E'
|
||||
},
|
||||
tableHeader: {
|
||||
flexDirection: 'row',
|
||||
backgroundColor: '#3E8F5A',
|
||||
fontWeight: 'bold',
|
||||
paddingVertical: 8,
|
||||
paddingHorizontal: 5,
|
||||
borderTopLeftRadius: 10,
|
||||
borderTopRightRadius: 10,
|
||||
},
|
||||
headerCell: {
|
||||
paddingHorizontal: 5,
|
||||
color: '#ffffff',
|
||||
fontWeight: 'bold',
|
||||
fontSize: 12,
|
||||
},
|
||||
row: {
|
||||
flexDirection: 'row',
|
||||
paddingVertical: 6,
|
||||
paddingHorizontal: 5,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: '#D5D8DC'
|
||||
},
|
||||
cell: {
|
||||
paddingHorizontal: 5,
|
||||
fontSize: 9,
|
||||
color: '#2C3E50'
|
||||
}
|
||||
});
|
||||
|
||||
const parseDate = (dateStr) => {
|
||||
if (!dateStr) return '';
|
||||
const [y, m, d] = dateStr.split('-');
|
||||
return `${d}/${m}/${y}`;
|
||||
};
|
||||
|
||||
export const SociosPDF = ({ socios }) => (
|
||||
<Document>
|
||||
<Page size="A4" orientation="landscape" style={styles.page}>
|
||||
<View style={styles.headerContainer}>
|
||||
<Image src={"/images/logo.png"} style={styles.logo} />
|
||||
<View style={styles.headerText}>
|
||||
<Text style={styles.header}>Listado de socios</Text>
|
||||
<Text style={styles.subHeader}>Asociación Huertos La Salud - Bellavista • Generado el {new Date().toLocaleDateString()} a las {new Date().toLocaleTimeString()}</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View style={styles.tableHeader}>
|
||||
<Text style={[styles.headerCell, { flex: 0.2 }]}>S</Text>
|
||||
<Text style={[styles.headerCell, { flex: 0.2 }]}>H</Text>
|
||||
<Text style={[styles.headerCell, { flex: 3 }]}>Nombre</Text>
|
||||
<Text style={[styles.headerCell, { flex: 1 }]}>DNI</Text>
|
||||
<Text style={[styles.headerCell, { flex: 1 }]}>Teléfono</Text>
|
||||
<Text style={[styles.headerCell, { flex: 3 }]}>Email</Text>
|
||||
<Text style={[styles.headerCell, { flex: 1 }]}>Alta</Text>
|
||||
<Text style={[styles.headerCell, { flex: 1 }]}>Tipo</Text>
|
||||
</View>
|
||||
|
||||
{socios.map((socio, idx) => (
|
||||
<View
|
||||
key={idx}
|
||||
style={[
|
||||
styles.row,
|
||||
{ backgroundColor: idx % 2 === 0 ? '#ECF0F1' : '#FDFEFE' },
|
||||
{ borderBottomLeftRadius: idx === socios.length - 1 ? 10 : 0 },
|
||||
{ borderBottomRightRadius: idx === socios.length - 1 ? 10 : 0 },
|
||||
]}
|
||||
>
|
||||
<Text style={[styles.cell, { flex: 0.2 }]}>{socio?.member_number}</Text>
|
||||
<Text style={[styles.cell, { flex: 0.2 }]}>{socio?.plot_number}</Text>
|
||||
<Text style={[styles.cell, { flex: 3 }]}>{socio?.display_name}</Text>
|
||||
<Text style={[styles.cell, { flex: 1 }]}>{socio?.dni}</Text>
|
||||
<Text style={[styles.cell, { flex: 1 }]}>{socio?.phone}</Text>
|
||||
<Text style={[styles.cell, { flex: 3 }]}>{socio?.email || ''}</Text>
|
||||
<Text style={[styles.cell, { flex: 1 }]}>{parseDate(socio?.created_at?.split('T')[0] || '')}</Text>
|
||||
<Text style={[styles.cell, { flex: 1 }]}>
|
||||
{(() => {
|
||||
switch (socio?.type) {
|
||||
case 0: return 'L. Espera';
|
||||
case 1: return 'Hortelano';
|
||||
case 2: return 'Invernadero';
|
||||
case 3: return 'Colaborador';
|
||||
default: return 'Desconocido';
|
||||
}
|
||||
})()}
|
||||
</Text>
|
||||
</View>
|
||||
))}
|
||||
</Page>
|
||||
</Document>
|
||||
);
|
||||
54
src/components/Socios/TipoSocioDropdown.jsx
Normal file
54
src/components/Socios/TipoSocioDropdown.jsx
Normal file
@@ -0,0 +1,54 @@
|
||||
import AnimatedDropdown from '../AnimatedDropdown';
|
||||
import { Image } from 'react-bootstrap';
|
||||
|
||||
const tipos = [
|
||||
{ value: 0, label: 'Lista de espera', icon: 'list.svg' },
|
||||
{ value: 1, label: 'Hortelano', icon: 'farmer.svg' },
|
||||
{ value: 2, label: 'Hortelano+Invernadero', icon: 'green_house.svg' },
|
||||
{ value: 3, label: 'Colaborador', icon: 'join.svg' },
|
||||
{ value: 4, label: 'Subvención', icon: 'subvencion4.svg' },
|
||||
{ value: 5, label: 'Informático', icon: 'programmer.svg' }
|
||||
];
|
||||
|
||||
const basePath = '/images/icons/';
|
||||
|
||||
const TipoSocioDropdown = ({ value, onChange }) => {
|
||||
const selected = tipos.find(t => t.value === value) || tipos[0];
|
||||
|
||||
return (
|
||||
<AnimatedDropdown
|
||||
trigger={
|
||||
<button className="btn p-0 border-0 bg-transparent">
|
||||
<Image
|
||||
src={basePath + selected.icon}
|
||||
width={36}
|
||||
className="rounded me-3"
|
||||
alt={selected.label}
|
||||
/>
|
||||
</button>
|
||||
}
|
||||
className="w-auto"
|
||||
>
|
||||
{({ closeDropdown }) => (
|
||||
<>
|
||||
{tipos.map(t => (
|
||||
<div
|
||||
key={t.value}
|
||||
className={`dropdown-item d-flex align-items-center`}
|
||||
style={{ width: '100%', minWidth: '160px' }}
|
||||
onClick={() => {
|
||||
onChange(t.value);
|
||||
closeDropdown();
|
||||
}}
|
||||
>
|
||||
<img src={basePath + t.icon} width={24} height={24} alt={t.label} className='me-3' />
|
||||
{t.label}
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</AnimatedDropdown>
|
||||
);
|
||||
};
|
||||
|
||||
export default TipoSocioDropdown;
|
||||
148
src/components/Solicitudes/PreUserForm.jsx
Normal file
148
src/components/Solicitudes/PreUserForm.jsx
Normal file
@@ -0,0 +1,148 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { Form, Row, Col, Button } from 'react-bootstrap';
|
||||
import { useDataContext } from '../../hooks/useDataContext';
|
||||
import { Alert } from 'react-bootstrap';
|
||||
import PropTypes from 'prop-types';
|
||||
|
||||
const PreUserForm = ({ onSubmit, userType, plotNumber, errors = {} }) => {
|
||||
const { getData } = useDataContext();
|
||||
const fetchedOnce = useRef(false);
|
||||
|
||||
const [form, setForm] = useState({
|
||||
user_name: '',
|
||||
display_name: '',
|
||||
dni: '',
|
||||
phone: '',
|
||||
email: '',
|
||||
address: '',
|
||||
zip_code: '',
|
||||
city: '',
|
||||
member_number: '',
|
||||
plot_number: plotNumber,
|
||||
type: userType,
|
||||
status: 1,
|
||||
role: 0
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const fetchLastNumber = async () => {
|
||||
if (fetchedOnce.current) return;
|
||||
fetchedOnce.current = true;
|
||||
|
||||
try {
|
||||
const { data, error } = await getData("https://api.huertosbellavista.es/v1/members/latest-number");
|
||||
if (error) throw new Error(error);
|
||||
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
member_number: data.lastMemberNumber + 1
|
||||
}));
|
||||
} catch (err) {
|
||||
console.error("Error al obtener el número de socio:", err);
|
||||
}
|
||||
};
|
||||
|
||||
fetchLastNumber();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const trimmedName = form.display_name?.trim() ?? "";
|
||||
|
||||
const nuevoUsername = trimmedName
|
||||
? trimmedName.split(' ')[0].toLowerCase() : "";
|
||||
|
||||
if (form.user_name !== nuevoUsername) {
|
||||
setForm(prev => ({ ...prev, user_name: nuevoUsername }));
|
||||
}
|
||||
}, [form.member_number, form.display_name, form.user_name]);
|
||||
|
||||
const handleChange = (e) => {
|
||||
const { name, value, type } = e.target;
|
||||
let updatedValue = value;
|
||||
|
||||
if (name === 'display_name' || name === 'dni') {
|
||||
updatedValue = value.toUpperCase();
|
||||
}
|
||||
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
[name]: type === 'number' ? parseInt(updatedValue) || '' : updatedValue
|
||||
}));
|
||||
};
|
||||
|
||||
const handleSubmit = (e) => {
|
||||
e.preventDefault();
|
||||
if (onSubmit) onSubmit(form);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{errors.general && <Alert variant="danger" className="my-2">{errors.general}</Alert>}
|
||||
|
||||
<Form onSubmit={handleSubmit} className="p-3 px-md-4">
|
||||
<Row className="gy-3">
|
||||
|
||||
{[
|
||||
{ label: 'Nombre completo', name: 'display_name', type: 'text', required: true },
|
||||
{ label: 'Nombre de usuario', name: 'user_name', type: 'text', required: true },
|
||||
{ label: 'DNI', name: 'dni', type: 'text', required: true, maxLength: 9 },
|
||||
{ label: 'Teléfono', name: 'phone', type: 'tel', required: true },
|
||||
{ label: 'Correo electrónico', name: 'email', type: 'email', required: true },
|
||||
{ label: 'Domicilio', name: 'address', type: 'text' },
|
||||
{ label: 'Código Postal', name: 'zip_code', type: 'text' },
|
||||
{ label: 'Ciudad', name: 'city', type: 'text' }
|
||||
].map(({ label, name, type, required, maxLength }) => (
|
||||
<Col md={4} key={name}>
|
||||
<Form.Group>
|
||||
<Form.Label className="fw-semibold">{label}</Form.Label>
|
||||
<Form.Control
|
||||
className="themed-input shadow-sm"
|
||||
type={type}
|
||||
name={name}
|
||||
value={form[name]}
|
||||
onChange={handleChange}
|
||||
required={required}
|
||||
maxLength={maxLength}
|
||||
isInvalid={!!errors[name]}
|
||||
/>
|
||||
<Form.Control.Feedback type="invalid">
|
||||
{errors[name]}
|
||||
</Form.Control.Feedback>
|
||||
</Form.Group>
|
||||
</Col>
|
||||
))}
|
||||
|
||||
<Col md={4}>
|
||||
<Form.Group>
|
||||
<Form.Label className="fw-semibold">Nº Socio</Form.Label>
|
||||
<Form.Control
|
||||
className="shadow-sm"
|
||||
disabled
|
||||
type="number"
|
||||
name="member_number"
|
||||
value={form.member_number}
|
||||
onChange={handleChange}
|
||||
/>
|
||||
</Form.Group>
|
||||
</Col>
|
||||
|
||||
<Col xs={12} className="text-center mt-3">
|
||||
<Button type="submit" variant="success" size="lg" className="px-5 shadow-sm">
|
||||
Enviar solicitud
|
||||
</Button>
|
||||
</Col>
|
||||
</Row>
|
||||
</Form>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
PreUserForm.propTypes = {
|
||||
userType: PropTypes.number.isRequired,
|
||||
plotNumber: PropTypes.number.isRequired,
|
||||
onSubmit: PropTypes.func.isRequired,
|
||||
errors: PropTypes.object
|
||||
};
|
||||
|
||||
export default PreUserForm;
|
||||
197
src/components/Solicitudes/SolicitudCard.jsx
Normal file
197
src/components/Solicitudes/SolicitudCard.jsx
Normal file
@@ -0,0 +1,197 @@
|
||||
import { Card, ListGroup, Button } from 'react-bootstrap';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import {
|
||||
faUser, faIdCard, faEnvelope, faPhone, faHome, faMapMarkerAlt, faHashtag,
|
||||
faSeedling, faUserShield, faCalendar,
|
||||
faTrash, faEllipsisVertical
|
||||
} from '@fortawesome/free-solid-svg-icons';
|
||||
import PropTypes from 'prop-types';
|
||||
import { motion as _motion } from 'framer-motion';
|
||||
import AnimatedDropdown from '../../components/AnimatedDropdown';
|
||||
import '../../css/SolicitudCard.css';
|
||||
|
||||
const MotionCard = _motion.create(Card);
|
||||
|
||||
const parseDate = (date) => {
|
||||
if (!date) return 'NO';
|
||||
const d = new Date(date);
|
||||
return `${d.getDate().toString().padStart(2, '0')}/${(d.getMonth() + 1).toString().padStart(2, '0')}/${d.getFullYear()}`;
|
||||
};
|
||||
|
||||
const getTipoSolicitud = (tipo) => ['Alta', 'Baja', 'Añadir Colaborador', 'Quitar Colaborador', 'Añadir parcela invernadero', 'Dejar parcela invernadero'][tipo] ?? 'Desconocido';
|
||||
const getEstadoSolicitud = (estado) => ['Pendiente', 'Aceptada', 'Rechazada'][estado] ?? 'Desconocido';
|
||||
|
||||
const getPFP = (tipo) => {
|
||||
const base = '/images/icons/';
|
||||
const map = {
|
||||
1: 'farmer.svg',
|
||||
2: 'green_house.svg',
|
||||
0: 'list.svg',
|
||||
3: 'join.svg',
|
||||
4: 'subvencion4.svg',
|
||||
5: 'programmer.svg'
|
||||
};
|
||||
return base + (map[tipo] || 'farmer.svg');
|
||||
};
|
||||
|
||||
const renderDescripcionSolicitud = (data, onProfile) => {
|
||||
const { request_type, request_status, requested_by_name, pre_display_name } = data;
|
||||
|
||||
switch (request_type) {
|
||||
case 0:
|
||||
if (requested_by_name) {
|
||||
return `${requested_by_name} quiere darse de alta.`;
|
||||
} else if (request_status !== 1 && pre_display_name) {
|
||||
return `${pre_display_name} quiere darse de alta.`;
|
||||
} else if (request_status !== 1) {
|
||||
return `Alguien quiere darse de alta.`;
|
||||
} else {
|
||||
return `Se ha aceptado esta solicitud de alta.`;
|
||||
}
|
||||
|
||||
case 1:
|
||||
return onProfile
|
||||
? "Has solicitado darte de baja."
|
||||
: requested_by_name
|
||||
? `${requested_by_name} quiere darse de baja.`
|
||||
: request_status !== 1
|
||||
? `Alguien quiere darse de baja.`
|
||||
: `Se ha aceptado esta solicitud de baja.`;
|
||||
|
||||
case 2:
|
||||
if (onProfile) {
|
||||
switch (request_status) {
|
||||
case 0: return "Has solicitado añadir un colaborador.";
|
||||
case 1: return "Tu solicitud de colaborador ha sido aceptada.";
|
||||
case 2: return "Tu solicitud de colaborador ha sido rechazada.";
|
||||
default: return "Solicitud de colaborador desconocida.";
|
||||
}
|
||||
} else {
|
||||
switch (request_status) {
|
||||
case 0:
|
||||
return requested_by_name
|
||||
? `${requested_by_name} quiere añadir a ${pre_display_name || "un colaborador"} como colaborador.`
|
||||
: `Alguien quiere añadir a ${pre_display_name || "un colaborador"} como colaborador.`;
|
||||
case 1:
|
||||
return `La solicitud de colaborador de ${requested_by_name || "alguien"} ha sido aceptada.`;
|
||||
case 2:
|
||||
return `La solicitud de colaborador de ${requested_by_name || "alguien"} ha sido rechazada.`;
|
||||
default:
|
||||
return "Solicitud de colaborador desconocida.";
|
||||
}
|
||||
}
|
||||
|
||||
case 3:
|
||||
return onProfile
|
||||
? "Has solicitado quitar tu colaborador."
|
||||
: requested_by_name
|
||||
? `${requested_by_name} quiere quitar su colaborador.`
|
||||
: request_status !== 1
|
||||
? `Alguien quiere quitar su colaborador.`
|
||||
: `Se ha aceptado esta solicitud de baja de colaborador.`;
|
||||
|
||||
case 4:
|
||||
return onProfile
|
||||
? "Has solicitado una parcela en el invernadero."
|
||||
: requested_by_name
|
||||
? `${requested_by_name} quiere una parcela en el invernadero.`
|
||||
: request_status !== 1
|
||||
? `Alguien quiere una parcela en el invernadero.`
|
||||
: `Se ha aceptado esta solicitud de parcela en el invernadero.`;
|
||||
|
||||
case 5:
|
||||
return onProfile
|
||||
? "Has solicitado dejar tu parcela del invernadero."
|
||||
: requested_by_name
|
||||
? `${requested_by_name} quiere dejar su parcela del invernadero.`
|
||||
: request_status !== 1
|
||||
? `Alguien quiere dejar su parcela del invernadero.`
|
||||
: `Se ha aceptado esta solicitud de salida del invernadero.`;
|
||||
|
||||
default:
|
||||
return "Tipo de solicitud desconocido.";
|
||||
}
|
||||
};
|
||||
|
||||
const SolicitudCard = ({ data, onAccept, onReject, onDelete, editable = true, onProfile = false }) => {
|
||||
const handleDelete = () => typeof onDelete === "function" && onDelete(data.request_id);
|
||||
|
||||
return (
|
||||
<MotionCard className="solicitud-card shadow-sm rounded-4 h-100">
|
||||
<Card.Header className="rounded-top-4 d-flex justify-content-between align-items-center">
|
||||
<div className="d-flex align-items-center">
|
||||
<img src={getPFP(data.pre_type)} width="36" className="rounded me-3" alt="PFP" />
|
||||
<div>
|
||||
<Card.Title className="mb-0">
|
||||
Solicitud #{data.request_id} - {getTipoSolicitud(data.request_type)}
|
||||
</Card.Title>
|
||||
<small className='state-small'>Estado: <strong>{getEstadoSolicitud(data.request_status)}</strong></small>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!onProfile && (
|
||||
<AnimatedDropdown
|
||||
className="end-0"
|
||||
buttonStyle="card-button"
|
||||
icon={<FontAwesomeIcon icon={faEllipsisVertical} className="fa-xl" />}>
|
||||
{({ closeDropdown }) => (
|
||||
<div className="dropdown-item d-flex align-items-center text-danger" onClick={() => { handleDelete(); closeDropdown(); }}>
|
||||
<FontAwesomeIcon icon={faTrash} className="me-2" />Eliminar
|
||||
</div>
|
||||
)}
|
||||
</AnimatedDropdown>
|
||||
)}
|
||||
</Card.Header>
|
||||
|
||||
<Card.Body>
|
||||
<ListGroup variant="flush" className="border rounded-3 mb-3">
|
||||
<ListGroup.Item>
|
||||
<FontAwesomeIcon icon={faCalendar} className="me-2" />
|
||||
Fecha de solicitud: <strong>{parseDate(data.request_created_at)}</strong>
|
||||
</ListGroup.Item>
|
||||
</ListGroup>
|
||||
|
||||
<ListGroup variant="flush" className="border rounded-3 mb-3">
|
||||
<ListGroup.Item>
|
||||
{renderDescripcionSolicitud(data, onProfile)}
|
||||
</ListGroup.Item>
|
||||
</ListGroup>
|
||||
|
||||
{data.pre_display_name && (
|
||||
<>
|
||||
<Card.Subtitle className="card-subtitle mt-3 mb-2">Datos del futuro socio</Card.Subtitle>
|
||||
<ListGroup variant="flush" className="border rounded-3">
|
||||
<ListGroup.Item><FontAwesomeIcon icon={faUser} className="me-2" />Nombre: <strong>{data.pre_display_name}</strong></ListGroup.Item>
|
||||
<ListGroup.Item><FontAwesomeIcon icon={faIdCard} className="me-2" />DNI: <strong>{data.pre_dni}</strong></ListGroup.Item>
|
||||
<ListGroup.Item><FontAwesomeIcon icon={faPhone} className="me-2" />Teléfono: <strong>{data.pre_phone}</strong></ListGroup.Item>
|
||||
<ListGroup.Item><FontAwesomeIcon icon={faEnvelope} className="me-2" />Email: <strong>{data.pre_email}</strong></ListGroup.Item>
|
||||
<ListGroup.Item><FontAwesomeIcon icon={faHome} className="me-2" />Dirección: <strong>{data.pre_address ?? 'NO'}</strong></ListGroup.Item>
|
||||
<ListGroup.Item><FontAwesomeIcon icon={faMapMarkerAlt} className="me-2" />Ciudad: <strong>{data.pre_city ?? 'NO'} ({data.pre_zip_code ?? 'NO'})</strong></ListGroup.Item>
|
||||
<ListGroup.Item><FontAwesomeIcon icon={faHashtag} className="me-2" />Nº socio: <strong>{data.pre_member_number ?? 'NO'}</strong> | Nº huerto: <strong>{data.pre_plot_number ?? 'NO'}</strong></ListGroup.Item>
|
||||
<ListGroup.Item><FontAwesomeIcon icon={faSeedling} className="me-2" />Tipo: <strong>{['Lista de Espera', 'Hortelano', 'Hortelano + Invernadero', 'Colaborador'][data.pre_type]}</strong></ListGroup.Item>
|
||||
<ListGroup.Item><FontAwesomeIcon icon={faUserShield} className="me-2" />Rol: <strong>{['Usuario', 'Admin', 'Desarrollador'][data.pre_role]}</strong></ListGroup.Item>
|
||||
</ListGroup>
|
||||
</>
|
||||
)}
|
||||
|
||||
{editable && data.request_status === 0 && (
|
||||
<div className="d-flex justify-content-end gap-2 mt-3">
|
||||
<Button variant="danger" size="sm" onClick={() => onReject?.(data)}>Rechazar</Button>
|
||||
<Button variant="success" size="sm" onClick={() => onAccept?.(data)}>Aceptar</Button>
|
||||
</div>
|
||||
)}
|
||||
</Card.Body>
|
||||
</MotionCard>
|
||||
);
|
||||
};
|
||||
|
||||
SolicitudCard.propTypes = {
|
||||
data: PropTypes.object.isRequired,
|
||||
onAccept: PropTypes.func,
|
||||
onReject: PropTypes.func,
|
||||
onDelete: PropTypes.func,
|
||||
editable: PropTypes.bool,
|
||||
onProfile: PropTypes.bool
|
||||
};
|
||||
|
||||
export default SolicitudCard;
|
||||
24
src/components/SpanishDateTimePicker.jsx
Normal file
24
src/components/SpanishDateTimePicker.jsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import DatePicker, { registerLocale } from 'react-datepicker';
|
||||
import es from 'date-fns/locale/es';
|
||||
|
||||
import 'react-datepicker/dist/react-datepicker.css';
|
||||
|
||||
registerLocale('es', es);
|
||||
|
||||
const SpanishDateTimePicker = ({ selected, onChange }) => {
|
||||
return (
|
||||
<DatePicker
|
||||
selected={selected}
|
||||
onChange={onChange}
|
||||
showTimeSelect
|
||||
timeFormat="HH:mm"
|
||||
timeIntervals={15}
|
||||
dateFormat="dd/MM/yyyy HH:mm"
|
||||
timeCaption="Hora"
|
||||
locale="es"
|
||||
className="form-control themed-input"
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default SpanishDateTimePicker;
|
||||
18
src/components/ThemeButton.jsx
Normal file
18
src/components/ThemeButton.jsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import { useTheme } from "../hooks/useTheme.js";
|
||||
import "../css/ThemeButton.css";
|
||||
|
||||
export default function ThemeButton({ className, onlyIcon}) {
|
||||
const { theme, toggleTheme } = useTheme();
|
||||
|
||||
return (
|
||||
<button className={`theme-toggle ${className}`} onClick={toggleTheme}>
|
||||
{
|
||||
onlyIcon ? (
|
||||
theme === "dark" ? ("🌞") : ("🌙")
|
||||
) : (
|
||||
theme === "dark" ? ("🌞 tema claro") : ("🌙 tema oscuro")
|
||||
)
|
||||
}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user