Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 49 additions & 40 deletions backend/controllers/sellDetails.controllers.js
Original file line number Diff line number Diff line change
@@ -1,59 +1,68 @@
const pool = require('../db');
const axios = require('axios');
// Controlador en tu backend
const pool= require ('../db')

const getSellAndClientDetails = async (req, res) => {
// Controlador para encontrar los detalles de la venta según id_detalle
const getDetalleVentaById = async (req, res) => {
try {
const { id_detalle } = req.params;

// Primero, obtén el id_venta basado en el id_detalle
const sellDetailsQuery = 'SELECT * FROM detalleventa WHERE id_detalle = $1';
const sellDetailsResult = await pool.query(sellDetailsQuery, [id_detalle]);
const query = 'SELECT * FROM detalleventa WHERE id_detalle = $1';
const result = await pool.query(query, [id_detalle]);

if (sellDetailsResult.rows.length === 0) {
if (result.rows.length === 0) {
return res.status(404).json({ message: 'Detalle de venta no encontrado.' });
}

// Después, usa id_venta para obtener dni_cliente de la tabla venta
const id_venta = sellDetailsResult.rows[0].id_venta;
const ventaQuery = 'SELECT dni_cliente FROM venta WHERE id_venta = $1';
const ventaResult = await pool.query(ventaQuery, [id_venta]);
res.json(result.rows[0]);
} catch (error) {
console.error('Error al obtener el detalle de la venta:', error);
res.status(500).json({ error: 'Error interno del servidor' });
}
};

if (ventaResult.rows.length === 0) {
return res.status(404).json({ message: 'Venta no encontrada.' });
}
// Controlador para obtener id_venta a partir de id_detalle
const getIdVentaByIdDetalle = async (req, res) => {
try {
const { id_detalle } = req.params;
const query = 'SELECT id_venta FROM detalleventa WHERE id_detalle = $1';
const result = await pool.query(query, [id_detalle]);

const dniCliente = ventaResult.rows[0].dni_cliente;
if (!dniCliente) {
return res.status(404).json({ message: 'DNI del cliente no encontrado.' });
if (result.rows.length === 0) {
return res.status(404).json({ message: 'Detalle de venta no encontrado.' });
}

// Finalmente, con el dni_cliente obtén la información del cliente de la API externa
const clientResponse = await axios.get(`https://clientemodulocrm.onrender.com/clientes/buscarPorDNI/${dniCliente}`);
if (!clientResponse.data) {
return res.status(404).json({ message: 'Datos del cliente no encontrados.' });
// Extrae id_venta de los resultados y devuélvelo
const id_venta = result.rows[0].id_venta;
res.json({ id_venta }); // Devuelve el id_venta
} catch (error) {
console.error('Error al obtener el id_venta:', error);
res.status(500).json({ error: 'Error interno del servidor' });
}
};

// Controlador para obtener dni_cliente a partir de id_venta
const getDniClienteByIdVenta = async (req, res) => {
try {
const { id_venta } = req.params;
const query = 'SELECT dni_cliente FROM venta WHERE id_venta = $1';
const result = await pool.query(query, [id_venta]);

if (result.rows.length === 0) {
return res.status(404).json({ message: 'Cliente no encontrado para la venta.' });
}

const cliente = {
nombre: clientResponse.data.nombre,
apellido: clientResponse.data.apellido,
correo: clientResponse.data.correo,
sexo: clientResponse.data.sexo
// Incluye aquí otros campos que necesites
};

// Combina los detalles de venta con la información del cliente y envía la respuesta
const responseData = {
detalleVenta: sellDetailsResult.rows[0],
cliente: cliente
};

res.json(responseData);
const dni_cliente = result.rows[0].dni_cliente;
res.json({ dni_cliente }); // Devuelve el dni_cliente
} catch (error) {
console.error('Error al obtener detalles de venta y cliente:', error);
console.error('Error al obtener el dni del cliente:', error);
res.status(500).json({ error: 'Error interno del servidor' });
}
};




module.exports = {
getSellAndClientDetails
};
getDetalleVentaById,
getIdVentaByIdDetalle,
getDniClienteByIdVenta
}
12 changes: 9 additions & 3 deletions backend/routes/task.routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const {associate, getLineas, pagoLinea, atrasoLinea, cancelarLinea, searchLinea,
const {searchbilldni, searchbillnumber, searchbillid, createbill, searchpaybilldni, searchpaybillnumero, paybill, updateBill, suspendBill}= require('../controllers/bills.controllers')
const {searchWarranty}= require('../controllers/warranty.controllers')
const {getSellDetailsById, getLastSell}= require('../controllers/searchById.controllers')
const { getSellAndClientDetails } = require('../controllers/sellDetails.controllers');
const { getDetalleVentaById, getIdVentaByIdDetalle, getDniClienteByIdVenta } = require('../controllers/sellDetails.controllers');
const {createReport}= require('../controllers/report.controllers')

const router = Router();
Expand Down Expand Up @@ -121,7 +121,7 @@ router.post('/updatebill/:numero_linea', updateBill)

router.get('/searchwarranty/:id_garantia', searchWarranty)

module.exports = router;


//Intentar aplicar mostrar equipos comprados

Expand All @@ -135,4 +135,10 @@ router.get('/sell/last', getLastSell);

router.get('/selldetails/:id_detalle', getSellDetailsById);

router.get('/selldetailsbyid/:id_detalle', getSellAndClientDetails);
router.get('/selldetailsbyid/:id_detalle', getDetalleVentaById);

router.get('/idventabyid/:id_detalle', getIdVentaByIdDetalle);

router.get('/clientebyid/:id_venta', getDniClienteByIdVenta);

module.exports = router;
168 changes: 121 additions & 47 deletions frontend/src/components/pages/imprimirventa/verdetalles.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,77 +7,151 @@ import jsPDF from 'jspdf';
const SellDetails = () => {
const { id_detalle } = useParams();
const [details, setDetails] = useState(null);
const [client, setClient] = useState(null);
const [cliente, setCliente] = useState(null);
const [error, setError] = useState('');
const [isButtonVisible, setIsButtonVisible] = useState(true);

useEffect(() => {
const fetchDetails = async () => {
try {
const detailsResponse = await axios.get(`https://modulo-ventas.onrender.com/selldetails/${id_detalle}`);
setDetails(detailsResponse.data);

if (detailsResponse.data) {
const clientResponse = await axios.get(`https://modulo-ventas.onrender.com/searchdni/${detailsResponse.data.dni_cliente}`);
setClient(clientResponse.data);
const SellDetails = () => {
const { id_detalle } = useParams();
const [details, setDetails] = useState(null);
const [cliente, setCliente] = useState(null);
const [error, setError] = useState('');

useEffect(() => {
const fetchDetails = async () => {
try {
// Obtener los detalles de la venta
const response = await axios.get(`https://modulo-ventas.onrender.com/selldetailsbyid/${id_detalle}`);
setDetails(response.data);

// Obtener id_venta a partir de id_detalle
const ventaResponse = await axios.get(`https://modulo-ventas.onrender.com/idventabyid/${id_detalle}`);
const id_venta = ventaResponse.data.id_venta;

// Obtener dni_cliente usando id_venta
const clienteResponse = await axios.get(`https://modulo-ventas.onrender.com/clientebyid/${id_venta}`);
const dni_cliente = clienteResponse.data.dni_cliente;

// Obtener detalles del cliente usando dni_cliente
if (dni_cliente) {
const clientDetailsResponse = await axios.get(`https://clientemodulocrm.onrender.com/clientes/buscarPorDNI/${dni_cliente}`);
setCliente(clientDetailsResponse.data);
}

} catch (error) {
console.error('Error al obtener los detalles de la venta:', error);
setError('Ocurrió un error al obtener los detalles de la venta.');
}
} catch (err) {
console.error('Error al obtener los detalles de la venta o el cliente:', err);
setError('Ocurrió un error al obtener los detalles de la venta o la información del cliente.');
}
};

fetchDetails();
}, [id_detalle]);
};

fetchDetails();
}, [id_detalle]);
}

const downloadPdfDocument = () => {
setIsButtonVisible(false); // Ocultar el botón antes de generar el PDF

const domElement = document.getElementById('boletaContainer');
html2canvas(domElement, {
onclone: (document) => {
document.getElementById('boletaContainer').style.visibility = 'visible';
}
}).then((canvas) => {
html2canvas(domElement).then((canvas) => {
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF();
pdf.addImage(imgData, 'PNG', 0, 0);
pdf.save('boleta.pdf');

setIsButtonVisible(true); // Mostrar el botón nuevamente
});
};

if (error) {
return <p>{error}</p>;
}

if (!details || !client) {
if (!details) {
return <p>Cargando...</p>;
}

return (
<div>
<div id="boletaContainer" className="boleta-container">
<div id='boletaContainer' style={boletaStyle}>
<div style={headerStyle}>
<h1>Boleta de Venta</h1>
<div className="cliente-info">
<h2>Información del Cliente</h2>
<p>Nombre: {client.nombre}</p>
<p>Apellido: {client.apellido}</p>
<p>DNI: {client.dni}</p>
<p>Correo: {client.correo}</p>
<p>Sexo: {client.sexo}</p>
</div>

<div className="venta-info">
<h2>Detalles de la Venta</h2>
<p>ID Venta: {details.id_venta}</p>
<p>ID Detalle: {details.id_detalle}</p>
<p>ID Producto: {details.id_producto}</p>
<p>Cantidad: {details.cantidad}</p>
<p>ID Garantía: {details.id_garantia}</p>
<p>Tipo: {details.tipo}</p>
<p>Tiempo de Garantía: {details.tiempo_garantia}</p>
</div>
</div>
<button onClick={downloadPdfDocument}>Descargar Boleta</button>
<div style={detailStyle}>
<span style={labelStyle}>ID Detalle:</span>
<span>{details.id_detalle}</span>
</div>
<div style={detailStyle}>
<span style={labelStyle}>ID Venta:</span>
<span>{details.id_venta}</span>
</div>
<div style={detailStyle}>
<span style={labelStyle}>ID Producto:</span>
<span>{details.id_producto}</span>
</div>
<div style={detailStyle}>
<span style={labelStyle}>Tipo:</span>
<span>{details.tipo}</span>
</div>
<div style={detailStyle}>
<span style={labelStyle}>Cantidad:</span>
<span>{details.cantidad}</span>
</div>
<div style={detailStyle}>
<span style={labelStyle}>ID Garantía:</span>
<span>{details.id_garantia}</span>
</div>
<div style={detailStyle}>
<span style={labelStyle}>Tiempo de Garantía:</span>
<span>{details.tiempo_garantia}</span>
</div>
<div style={detailStyle}>
<span style={labelStyle}>Coste total:</span>
<span>{details.coste_total}</span>
</div>
<div style={detailStyle}>
<span style={labelStyle}>Nombre del Cliente:</span>
<span>{cliente.nombre}</span>
</div>
<div style={detailStyle}>
<span style={labelStyle}>Apellido del Cliente:</span>
<span>{cliente.apellido}</span>
</div>
<div style={detailStyle}>
<span style={labelStyle}>Sexo del Cliente:</span>
<span>{cliente.sexo}</span>
</div>
<div style={detailStyle}>
<span style={labelStyle}>Correo del Cliente:</span>
<span>{cliente.correo}</span>
</div>
{isButtonVisible && <button onClick={downloadPdfDocument}>Descargar Boleta</button>}
</div>
);
};

export default SellDetails;
const boletaStyle = {
maxWidth: '600px',
margin: '20px auto',
padding: '20px',
border: '1px solid #ddd',
borderRadius: '5px',
backgroundColor: '#f9f9f9',
fontFamily: 'Arial, sans-serif',
color: '#333',
};

const headerStyle = {
textAlign: 'center',
marginBottom: '20px',
};

const detailStyle = {
margin: '10px 0',
display: 'flex',
justifyContent: 'space-between',
};

const labelStyle = {
fontWeight: 'bold',
};

export default SellDetails;