Update Supabase integration for ticket sales and reporting; downgrade jsPDF version

This commit is contained in:
SirRobert-1 2025-03-12 23:00:08 -06:00
parent 2c6cd9ba78
commit d0c9f59963
5 changed files with 778 additions and 188 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

@ -52,9 +52,11 @@ function Informacion() {
};
const fetchAsientos = async () => {
let { data, error } = await supabaseClient.from("asientos").select("*"); // Include price in the select
let { data, error } = await supabaseClient
.from("asientos")
.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)),
@ -77,10 +79,16 @@ function Informacion() {
const handleAsientoChange = (asiento) => {
setAsientoSeleccionado(asiento);
console.log(asiento);
const selectedAsiento = numeroAsiento.find(
(item) => item.numero === parseInt(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 = () => {
@ -176,18 +184,23 @@ function Informacion() {
</SelectTrigger>
<SelectContent>
{filteredAsientos.map((asiento) => (
<SelectItem key={asiento.id} value={asiento.numero}>
<SelectItem
key={asiento.asiento_id}
value={asiento.numero.toString()}
>
{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">

View File

@ -1,16 +1,22 @@
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 dynamic from "next/dynamic";
import {
BarChart,
Bar,
XAxis,
YAxis,
Tooltip,
ResponsiveContainer,
} from "recharts";
import { Button } from "@/components/ui/button";
const html2canvas = dynamic(() => import("html2canvas"), {
ssr: false,
});
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 +24,7 @@ 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("*");
if (error) {
console.error("Error al obtener las ventas:", error.message);
} else {
@ -62,12 +68,19 @@ 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 {
const input = document.getElementById("reporte");
const canvas = await html2canvas(input);
const imgData = canvas.toDataURL("image/png");
// Dynamic import of jsPDF
const { default: jsPDF } = await import("jspdf");
const pdf = new jsPDF("p", "mm", "a4");
pdf.addImage(imgData, "PNG", 10, 10, 190, 0);
pdf.save("Reporte_Ventas.pdf");
} catch (error) {
console.error("Error generating PDF:", error);
}
};
// Datos filtrados según el filtro seleccionado
@ -78,7 +91,9 @@ 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>
@ -124,7 +139,10 @@ export default function Reporte() {
{/* Sección de Gráfico */}
<TabPanel>
<ResponsiveContainer width="100%" height={300}>
<BarChart data={ventasFiltradas} margin={{ top: 20, right: 30, left: 20, bottom: 5 }}>
<BarChart
data={ventasFiltradas}
margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
>
<XAxis dataKey="venta_id" />
<YAxis />
<Tooltip />

View File

@ -15,6 +15,7 @@ import {
SelectContent,
SelectItem,
} from "@/components/ui/select";
import { supabaseClient } from "@/utils/supabase";
export default function Carrito() {
const [carrito, setCarrito] = useState([]);
@ -51,7 +52,39 @@ export default function Carrito() {
}
try {
// Aquí iría la lógica de pago
// Create sales records for each item in cart
const ventasData = carrito.map((item) => ({
concierto_id: item.id,
asiento_numero: parseInt(item.asiento),
precio: item.precio,
metodo_pago: selectedPaymentMethod,
fecha_venta: new Date().toISOString(),
estado: "completado",
}));
const { data, error } = await supabaseClient
.from("ventas")
.insert(ventasData)
.select();
if (error) {
throw error;
}
// Update asientos estado to 'ocupado'
const asientosUpdates = carrito.map((item) => ({
numero: parseInt(item.asiento),
estado: "ocupado",
}));
const { error: asientosError } = await supabaseClient
.from("asientos")
.upsert(asientosUpdates, { onConflict: "numero" });
if (asientosError) {
throw asientosError;
}
alert("Pago realizado con éxito");
localStorage.removeItem("carrito");
setCarrito([]);
@ -63,30 +96,6 @@ export default function Carrito() {
}
};
/*const pagar = async () => {
try {
const response = await fetch("/api/comprar-boletos", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ boletos: carrito }),
});
if (!response.ok) {
throw new Error("Error al procesar el pago");
}
alert("Compra realizada con éxito");
localStorage.removeItem("carrito");
setCarrito([]);
router.push("/");
} catch (error) {
console.error("Error en la compra:", error);
alert("Hubo un problema al realizar la compra");
}
};*/
return (
<div className="w-screen flex flex-col items-center justify-center">
<div className="w-[80%] my-5">