Compare commits

...

4 Commits

5 changed files with 993 additions and 269 deletions

File diff suppressed because it is too large Load Diff

View File

@ -19,7 +19,7 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"html2canvas": "^1.4.1",
"jspdf": "^3.0.0",
"jspdf": "^1.5.3",
"lucide-react": "^0.475.0",
"next": "15.1.7",
"react": "^19.0.0",

View File

@ -54,9 +54,9 @@ function Informacion() {
const fetchAsientos = async () => {
let { data, error } = await supabaseClient
.from("asientos")
.select("numero_asiento, categoria, precio"); // Include price in the select
.select("asiento_id, numero, categoria, precio");
if (error) {
console.error(error);
console.error("Error fetching asientos:", error);
} else {
const uniqueCategories = [
...new Set(data.map((asiento) => asiento.categoria)),
@ -79,10 +79,16 @@ function Informacion() {
const handleAsientoChange = (asiento) => {
setAsientoSeleccionado(asiento);
console.log(asiento);
const selectedAsiento = numeroAsiento.find(
(item) => item.numero_asiento === asiento
(item) =>
item.numero === parseInt(asiento) &&
item.categoria === selectedCategoria
);
setPrecioAsiento(selectedAsiento?.precio || null); // Set the price of the selected seat
if (selectedAsiento) {
setPrecioAsiento(selectedAsiento.precio);
console.log("Precio del asiento:", selectedAsiento.precio);
}
};
const handleAgregarAlCarrito = () => {
@ -90,20 +96,26 @@ function Informacion() {
alert("Selecciona un tipo de asiento antes de continuar.");
return;
}
const carritoActual = JSON.parse(localStorage.getItem("carrito")) || [];
const nuevoCarrito = [
...carritoActual,
{ ...selectedConcierto, asiento: asientoSeleccionado, precio: precioAsiento },
{
...selectedConcierto,
asiento: asientoSeleccionado,
precio: precioAsiento,
},
];
localStorage.setItem("carrito", JSON.stringify(nuevoCarrito));
setOpen(false);
};
const filteredAsientos = numeroAsiento
.filter((asiento) => asiento.categoria === selectedCategoria)
.sort((a, b) => a.numero_asiento - b.numero_asiento);
.filter((asiento) => {
return asiento.categoria === selectedCategoria;
})
.sort((a, b) => parseInt(a.numero) - parseInt(b.numero));
return (
<>
@ -123,7 +135,7 @@ function Informacion() {
<div
key={concierto.id}
className="flex items-center gap-4 p-4 border rounded-lg"
>
>
<img
src={`/images/${concierto.imagen || "default.jpeg"}`}
alt={concierto.nombre}
@ -141,8 +153,13 @@ function Informacion() {
</div>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent>
<DialogContent className="bg-white text-black">
<DialogHeader>
<img
src={`/images/default.jpeg`}
alt={""}
className="w-24 h-24 rounded-lg object-cover"
/>
<DialogTitle>{selectedConcierto?.nombre}</DialogTitle>
<p className="text-sm text-gray-600">{selectedConcierto?.fecha}</p>
</DialogHeader>
@ -168,18 +185,22 @@ function Informacion() {
<SelectContent>
{filteredAsientos.map((asiento) => (
<SelectItem
key={asiento.numero_asiento}
value={asiento.numero_asiento}
key={asiento.asiento_id}
value={asiento.numero.toString()}
>
{asiento.numero_asiento}
{asiento.numero}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label>
{precioAsiento !== null ? `Precio: $${precioAsiento}` : "Selecciona un asiento para ver el precio"}
<div className="space-y-4">
<Label className="block text-sm font-medium text-gray-700">
{selectedCategoria && asientoSeleccionado
? precioAsiento
? `Precio: $${precioAsiento}`
: "Precio no disponible"
: "Selecciona categoría y asiento para ver el precio"}
</Label>
</div>
<div className="flex justify-end gap-2 mt-4">
@ -194,4 +215,4 @@ function Informacion() {
);
}
export default Informacion;
export default Informacion;

View File

@ -1,16 +1,18 @@
import { useState, useEffect } from "react";
import { createClient } from "@supabase/supabase-js";
import { supabaseClient } from "@/utils/supabase";
import { Tab, Tabs, TabList, TabPanel } from "react-tabs";
import "react-tabs/style/react-tabs.css";
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer } from "recharts";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import { Tabs as ShadcnTabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
BarChart,
Bar,
XAxis,
YAxis,
Tooltip,
ResponsiveContainer,
} from "recharts";
import { Button } from "@/components/ui/button";
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
);
export default function Reporte() {
const [ventas, setVentas] = useState([]);
const [filtro, setFiltro] = useState("diario"); // Estado para el filtro de fecha (diario, semanal, mensual)
@ -18,7 +20,27 @@ export default function Reporte() {
// Función para obtener los datos de ventas de Supabase
useEffect(() => {
const fetchVentas = async () => {
const { data, error } = await supabase.from("ventas").select("*");
const { data, error } = await supabaseClient.from("ventas").select(`
venta_id,
fecha_venta,
monto,
boletos (
boleto_id,
comprador_nombre,
comprador_email,
conciertos (
nombre,
fecha,
salas (
nombre
)
),
asientos (
numero,
categoria
)
)
`);
if (error) {
console.error("Error al obtener las ventas:", error.message);
} else {
@ -62,12 +84,26 @@ export default function Reporte() {
// Función para generar el PDF
const generarPDF = async () => {
const input = document.getElementById("reporte");
const canvas = await html2canvas(input);
const imgData = canvas.toDataURL("image/png");
const pdf = new jsPDF("p", "mm", "a4");
pdf.addImage(imgData, "PNG", 10, 10, 190, 0);
pdf.save("Reporte_Ventas.pdf");
try {
// Dynamic imports for both libraries
const html2canvas = (await import('html2canvas')).default;
const jsPDF = (await import('jspdf')).default;
const element = document.getElementById("reporte");
const canvas = await html2canvas(element);
const data = canvas.toDataURL('image/png');
const pdf = new jsPDF();
const imgProperties = pdf.getImageProperties(data);
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = (imgProperties.height * pdfWidth) / imgProperties.width;
pdf.addImage(data, 'PNG', 0, 0, pdfWidth, pdfHeight);
pdf.save("Reporte_Ventas.pdf");
} catch (error) {
console.error("Error al generar PDF:", error);
alert("Error al generar el PDF");
}
};
// Datos filtrados según el filtro seleccionado
@ -78,60 +114,55 @@ export default function Reporte() {
<h1>Reporte de Ventas</h1>
{/* Botón para generar PDF */}
<button onClick={generarPDF}>Descargar PDF</button>
<Button onClick={generarPDF} className="">
Descargar PDF <img src="/pdf.svg" alt="" className="h-7 w-7" />
</Button>
{/* Filtros de fechas */}
<div>
<button onClick={() => setFiltro("diario")}>Diario</button>
<button onClick={() => setFiltro("semanal")}>Semanal</button>
<button onClick={() => setFiltro("mensual")}>Mensual</button>
</div>
<ShadcnTabs
defaultValue="diario"
className="w-[400px] mb-4"
onValueChange={(value) => setFiltro(value)}
>
<TabsList className="grid w-full grid-cols-3">
<TabsTrigger value="diario">Diario</TabsTrigger>
<TabsTrigger value="semanal">Semanal</TabsTrigger>
<TabsTrigger value="mensual">Mensual</TabsTrigger>
</TabsList>
</ShadcnTabs>
<Tabs>
<TabList>
<Tab>Tabla</Tab>
<Tab>Gráfico de Ventas</Tab>
</TabList>
{/* Sección de Tabla */}
<TabPanel>
<div id="reporte">
<table border="1">
<table border="1" className="m-10">
<thead>
<tr>
<th>ID Venta</th>
<th>ID Boleto</th>
<th>ID Vendedor</th>
<th>Fecha Venta</th>
<th>Monto</th>
<th className="pr-5">ID Venta</th>
<th className="pr-5">Fecha Venta</th>
<th className="pr-5">Asiento</th>
<th className="pr-5">Categoría</th>
<th className="pr-5">Monto</th>
</tr>
</thead>
<tbody>
{ventasFiltradas.map((venta) => (
<tr key={venta.venta_id}>
<td>{venta.venta_id}</td>
<td>{venta.boleto_id}</td>
<td>{venta.vendedor_id}</td>
<td>{new Date(venta.fecha_venta).toLocaleString()}</td>
<td>${venta.monto}</td>
</tr>
<td className="pr-5">{venta.venta_id}</td>
<td className="pr-5">{new Date(venta.fecha_venta).toLocaleString()}</td>
<td className="pr-5">{venta.boletos.asientos.numero}</td>
<td className="pr-5">{venta.boletos.asientos.categoria}</td>
<td className="pr-5">${venta.monto}</td>
</tr>
))}
</tbody>
</table>
</div>
</TabPanel>
{/* Sección de Gráfico */}
<TabPanel>
<ResponsiveContainer width="100%" height={300}>
<BarChart data={ventasFiltradas} margin={{ top: 20, right: 30, left: 20, bottom: 5 }}>
<XAxis dataKey="venta_id" />
<YAxis />
<Tooltip />
<Bar dataKey="monto" fill="#8884d8" />
</BarChart>
</ResponsiveContainer>
</TabPanel>
</Tabs>
</div>
);

View File

@ -1,12 +1,28 @@
import { useEffect, useState } from "react";
import { useRouter } from "next/router";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import Link from "next/link";
import {
Select,
SelectTrigger,
SelectValue,
SelectContent,
SelectItem,
} from "@/components/ui/select";
import { supabaseClient } from "@/utils/supabase";
export default function Carrito() {
const [carrito, setCarrito] = useState([]);
const [showDialog, setShowDialog] = useState(false);
const [showPaymentDialog, setShowPaymentDialog] = useState(false);
const [conciertoAEliminar, setConciertoAEliminar] = useState(null);
const [selectedPaymentMethod, setSelectedPaymentMethod] = useState("");
const router = useRouter();
useEffect(() => {
@ -16,7 +32,9 @@ export default function Carrito() {
const eliminarConcierto = () => {
if (conciertoAEliminar !== null) {
const nuevoCarrito = carrito.filter((_, index) => index !== conciertoAEliminar);
const nuevoCarrito = carrito.filter(
(_, index) => index !== conciertoAEliminar
);
localStorage.setItem("carrito", JSON.stringify(nuevoCarrito));
setCarrito(nuevoCarrito);
setShowDialog(false);
@ -27,85 +45,189 @@ export default function Carrito() {
return carrito.reduce((total, item) => total + (item.precio || 0), 0);
};
const pagar = async () => {
try {
const response = await fetch("/api/comprar-boletos", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ boletos: carrito }),
});
const handlePagar = async () => {
if (!selectedPaymentMethod) {
alert("Por favor seleccione un método de pago");
return;
}
if (!response.ok) {
throw new Error("Error al procesar el pago");
try {
// Create sales and ticket records for each item in cart
for (const item of carrito) {
// First create the ticket record
const { data: boletoData, error: boletoError } = await supabaseClient
.from("boletos")
.insert({
concierto_id: item.id,
categoria: "General", // You might want to make this dynamic
comprador_nombre: "Usuario", // Add form fields for this
comprador_email: "usuario@example.com", // Add form fields for this
asiento_id: item.asiento,
estado: "disponible",
})
.select()
.single();
if (boletoError) throw boletoError;
// Then create the sale record
const { data: ventaData, error: ventaError } = await supabaseClient
.from("ventas")
.insert({
boleto_id: boletoData.boleto_id,
fecha_venta: new Date().toISOString(),
monto: item.precio,
})
.select();
if (ventaError) throw ventaError;
// Update asiento status
const { error: asientoError } = await supabaseClient
.from("asientos")
.update({ estado: "ocupado" })
.eq("numero", item.asiento);
if (asientoError) throw asientoError;
}
alert("Compra realizada con éxito");
alert("Pago realizado con éxito");
localStorage.removeItem("carrito");
setCarrito([]);
setShowPaymentDialog(false);
router.push("/");
} catch (error) {
console.error("Error en la compra:", error);
alert("Hubo un problema al realizar la compra");
console.error("Error en el pago:", error);
alert("Hubo un problema al realizar el pago");
}
};
return (
<div className="p-4 max-w-3xl mx-auto bg-gray-900 text-white rounded-lg shadow-lg">
<h2 className="text-2xl font-bold mb-4">Carrito de Compras</h2>
{carrito.length === 0 ? (
<p className="text-gray-400">No hay conciertos en el carrito.</p>
) : (
carrito.map((item, index) => (
<div key={index} className="border p-4 mb-2 rounded-lg bg-gray-800">
<p className="text-lg font-semibold text-white">{item.nombre}</p>
<p className="text-sm text-gray-300">Fecha: {item.fecha}</p>
<p className="text-sm text-gray-300">Asiento: {item.asiento}</p>
<p className="text-sm text-gray-300">Precio: ${item.precio}</p>
<Button
className="mt-2 bg-red-500 hover:bg-red-600"
onClick={() => {
setConciertoAEliminar(index);
setShowDialog(true);
}}
>
Eliminar
</Button>
</div>
))
)}
<div className="w-screen flex flex-col items-center justify-center">
<div className="w-[80%] my-5">
<Link href={"/"}>
<Button className="bg-blue-500 hover:bg-blue-600">Volver</Button>
</Link>
</div>
<div className="mx-10 py-5 px-10 text-black rounded-lg shadow-lg w-[80%]">
<h2 className="text-2xl font-bold mb-4">Carrito de Compras</h2>
{carrito.length === 0 ? (
<p className="text-gray-400">No hay conciertos en el carrito.</p>
) : (
carrito.map((item, index) => (
<div key={index} className="border p-4 mb-2 rounded-lg bg-gray-800">
<p className="text-lg font-semibold text-white">{item.nombre}</p>
<p className="text-sm text-gray-300">Fecha: {item.fecha}</p>
<p className="text-sm text-gray-300">Asiento: {item.asiento}</p>
<p className="text-sm text-gray-300">Precio: ${item.precio}</p>
<Button
className="mt-2 bg-red-500 hover:bg-red-600"
onClick={() => {
setConciertoAEliminar(index);
setShowDialog(true);
}}
>
Eliminar
</Button>
</div>
))
)}
{carrito.length > 0 && (
<>
<p className="text-xl font-bold text-white mt-4">
Total: ${calcularTotal()}
</p>
<div className="flex justify-between mt-4">
<Button
className="bg-gray-500 hover:bg-gray-600"
onClick={() => router.push("/")}
>
Cancelar
</Button>
<Button
className="bg-green-500 hover:bg-green-600"
onClick={() => setShowPaymentDialog(true)}
>
Pagar
</Button>
</div>
</>
)}
{carrito.length > 0 && (
<>
<p className="text-xl font-bold text-white mt-4">Total: ${calcularTotal()}</p>
<div className="flex justify-between mt-4">
<Button
className="bg-gray-500 hover:bg-gray-600"
onClick={() => router.push("/")}
>
Cancelar
</Button>
<Button className="bg-green-500 hover:bg-green-600" onClick={pagar}>Pagar</Button>
</div>
</>
)}
<Dialog open={showDialog} onOpenChange={setShowDialog}>
{/* ...existing delete dialog code... */}
</Dialog>
<Dialog open={showDialog} onOpenChange={setShowDialog}>
<DialogContent>
<DialogHeader>
<DialogTitle>¿Estás seguro de eliminar este concierto?</DialogTitle>
</DialogHeader>
<div className="flex justify-end gap-2 mt-4">
<Button variant="outline" onClick={() => setShowDialog(false)}>
Cancelar
</Button>
<Button className="bg-red-500 hover:bg-red-600" onClick={eliminarConcierto}>
Eliminar
</Button>
</div>
</DialogContent>
</Dialog>
{/* Dialog para pago */}
<Dialog open={showPaymentDialog} onOpenChange={setShowPaymentDialog}>
<DialogContent className="bg-white text-black">
<DialogHeader>
<DialogTitle className="text-xl font-bold">
Seleccione método de pago
</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<Select onValueChange={setSelectedPaymentMethod}>
<SelectTrigger>
<SelectValue placeholder="Seleccione método de pago" />
</SelectTrigger>
<SelectContent>
<SelectItem value="tarjeta">
Tarjeta de Crédito/Débito
</SelectItem>
<SelectItem value="paypal">PayPal</SelectItem>
<SelectItem value="transferencia">
Transferencia Bancaria
</SelectItem>
</SelectContent>
</Select>
<div className="mt-4">
<p className="font-semibold">
Total a pagar: ${calcularTotal()}
</p>
</div>
<div className="flex justify-end gap-2 mt-4">
<Button
variant="outline"
onClick={() => setShowPaymentDialog(false)}
>
Cancelar
</Button>
<Button
className="bg-green-500 hover:bg-green-600 text-white"
onClick={handlePagar}
disabled={!selectedPaymentMethod}
>
Confirmar Pago
</Button>
</div>
</div>
</DialogContent>
</Dialog>
<Dialog open={showDialog} onOpenChange={setShowDialog}>
<DialogContent>
<DialogHeader>
<DialogTitle>
¿Estás seguro de eliminar este concierto?
</DialogTitle>
</DialogHeader>
<div className="flex justify-end gap-2 mt-4">
<Button variant="outline" onClick={() => setShowDialog(false)}>
Cancelar
</Button>
<Button
className="bg-red-500 hover:bg-red-600"
onClick={eliminarConcierto}
>
Eliminar
</Button>
</div>
</DialogContent>
</Dialog>
</div>
</div>
);
}
}