Compare commits

...

4 Commits

6 changed files with 914 additions and 271 deletions

File diff suppressed because it is too large Load Diff

View File

@ -19,11 +19,12 @@
"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",
"react-dom": "^19.0.0",
"react-tabs": "^6.1.0",
"recharts": "^2.15.1",
"tailwind-merge": "^3.0.2",
"tailwindcss-animate": "^1.0.7",

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,106 +1,156 @@
import React, { useState, useRef } from "react";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer } from "recharts";
import jsPDF from "jspdf";
import html2canvas from "html2canvas";
import { useState, useEffect } from "react";
import { supabaseClient } from "@/utils/supabase";
import { Tab, Tabs, TabList, TabPanel } from "react-tabs";
import "react-tabs/style/react-tabs.css";
import dynamic from "next/dynamic";
import {
BarChart,
Bar,
XAxis,
YAxis,
Tooltip,
ResponsiveContainer,
} from "recharts";
import { Button } from "@/components/ui/button";
const Reporte = () => {
const chartRef = useRef(null); // Referencia para capturar la gráfica
const html2canvas = dynamic(() => import("html2canvas"), {
ssr: false,
});
// Datos simulados de ventas
const ventasDiarias = [
{ fecha: "2025-03-01", boletos: 20 },
{ fecha: "2025-03-02", boletos: 35 },
{ fecha: "2025-03-03", boletos: 50 },
];
export default function Reporte() {
const [ventas, setVentas] = useState([]);
const [filtro, setFiltro] = useState("diario"); // Estado para el filtro de fecha (diario, semanal, mensual)
const ventasSemanales = [
{ semana: "Semana 1", boletos: 120 },
{ semana: "Semana 2", boletos: 150 },
{ semana: "Semana 3", boletos: 170 },
];
// Función para obtener los datos de ventas de Supabase
useEffect(() => {
const fetchVentas = async () => {
const { data, error } = await supabaseClient.from("ventas").select("*");
if (error) {
console.error("Error al obtener las ventas:", error.message);
} else {
console.log("Datos obtenidos:", data);
setVentas(data);
}
};
const ventasMensuales = [
{ mes: "Enero", boletos: 500 },
{ mes: "Febrero", boletos: 650 },
{ mes: "Marzo", boletos: 700 },
];
fetchVentas();
}, []);
const [selectedTab, setSelectedTab] = useState("diario");
// Función para filtrar las ventas según el rango de fechas
const filtrarVentas = () => {
const hoy = new Date();
let fechaInicio;
// Obtener datos según la pestaña activa
const getData = () => {
switch (selectedTab) {
switch (filtro) {
case "diario":
return ventasDiarias;
fechaInicio = new Date(hoy.setHours(0, 0, 0, 0)); // Inicio del día
return ventas.filter((venta) => {
const fechaVenta = new Date(venta.fecha_venta);
return fechaVenta >= fechaInicio;
});
case "semanal":
return ventasSemanales;
const inicioSemana = hoy.getDate() - hoy.getDay(); // Día lunes de esta semana
fechaInicio = new Date(hoy.setDate(inicioSemana));
return ventas.filter((venta) => {
const fechaVenta = new Date(venta.fecha_venta);
return fechaVenta >= fechaInicio;
});
case "mensual":
return ventasMensuales;
fechaInicio = new Date(hoy.getFullYear(), hoy.getMonth(), 1); // Primer día del mes
return ventas.filter((venta) => {
const fechaVenta = new Date(venta.fecha_venta);
return fechaVenta >= fechaInicio;
});
default:
return [];
return ventas;
}
};
// Calcular el total de boletos vendidos
const totalBoletos = getData().reduce((acc, item) => acc + item.boletos, 0);
// Función para generar y descargar el PDF
// Función para generar el PDF
const generarPDF = async () => {
const pdf = new jsPDF();
pdf.setFontSize(18);
pdf.text("Reporte de Ventas", 10, 10);
pdf.setFontSize(14);
pdf.text(`Tipo de Reporte: ${selectedTab.toUpperCase()}`, 10, 20);
pdf.text(`Total de Boletos Vendidos: ${totalBoletos}`, 10, 30);
// Capturar la gráfica como imagen
if (chartRef.current) {
const canvas = await html2canvas(chartRef.current);
try {
const input = document.getElementById("reporte");
const canvas = await html2canvas(input);
const imgData = canvas.toDataURL("image/png");
pdf.addImage(imgData, "PNG", 10, 40, 180, 90);
}
pdf.save(`reporte_${selectedTab}.pdf`);
// 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
const ventasFiltradas = filtrarVentas();
return (
<div className="w-full max-w-3xl mx-auto p-4">
<h2 className="text-2xl font-bold mb-4">Reporte de Ventas</h2>
<Tabs defaultValue="diario" onValueChange={setSelectedTab} className="w-full">
<TabsList className="flex space-x-2 mb-4">
<TabsTrigger value="diario">Diario</TabsTrigger>
<TabsTrigger value="semanal">Semanal</TabsTrigger>
<TabsTrigger value="mensual">Mensual</TabsTrigger>
<img
src="/pdf.svg"
alt="pdf"
className="h-7 w-7 cursor-pointer"
onClick={generarPDF}
/>
</TabsList>
<div>
<h1>Reporte de Ventas</h1>
<Card>
<CardHeader>
<CardTitle>
Total de Boletos Vendidos: <span className="text-blue-600">{totalBoletos}</span>
</CardTitle>
</CardHeader>
<CardContent ref={chartRef}>
<ResponsiveContainer width="100%" height={300}>
<BarChart data={getData()}>
<XAxis dataKey={selectedTab === "diario" ? "fecha" : selectedTab === "semanal" ? "semana" : "mes"} />
<YAxis />
<Tooltip />
<Bar dataKey="boletos" fill="#3b82f6" />
</BarChart>
</ResponsiveContainer>
</CardContent>
</Card>
{/* Botón para generar PDF */}
<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>
<Tabs>
<TabList>
<Tab>Tabla</Tab>
<Tab>Gráfico de Ventas</Tab>
</TabList>
{/* Sección de Tabla */}
<TabPanel>
<div id="reporte">
<table border="1">
<thead>
<tr>
<th>ID Venta</th>
<th>ID Boleto</th>
<th>ID Vendedor</th>
<th>Fecha Venta</th>
<th>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>
))}
</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>
);
};
export default Reporte;
}

View File

@ -1,24 +1,31 @@
import { supabaseClient } from "@/utils/supabase";
import { createClient } from "@supabase/supabase-js";
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
);
export default async function handler(req, res) {
if (req.method === "POST") {
if (req.method !== "POST") {
return res.status(405).json({ error: "Método no permitido" });
}
try {
const { boletos } = req.body;
try {
const { data, error } = await supabaseClient
.from("boletos_comprados")
.insert(boletos);
if (error) {
throw error;
}
res.status(200).json({ message: "Compra realizada con éxito", data });
} catch (error) {
console.error("Error al insertar boletos:", error);
res.status(500).json({ message: "Error al procesar la compra", error });
if (!boletos || boletos.length === 0) {
return res.status(400).json({ error: "No hay boletos para procesar" });
}
} else {
res.status(405).json({ message: "Método no permitido" });
const { data, error } = await supabase.from("ventas").insert(boletos);
if (error) {
throw error;
}
res.status(200).json({ message: "Boletos comprados con éxito", data });
} catch (error) {
console.error("Error en la API de compra:", error.message);
res.status(500).json({ error: error.message });
}
}
}

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">