Skip to content
Binary file added public/images/cuenca-catedral-calle.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/images/cuenca-panoramica.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/images/cuenca-parque-calderon.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
184 changes: 123 additions & 61 deletions src/app/api/boletos/verificar-qr/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,89 +5,151 @@ import { createClient } from '@/lib/supabase/server';
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { token } = body;
const rawToken = typeof body?.token === 'string' ? body.token.trim() : '';

if (!token) {
return NextResponse.json({ success: false, message: 'Boleto inválido: token vacío' }, { status: 400 });
if (!rawToken) {
return NextResponse.json(
{ success: false, message: 'Boleto inválido: código vacío' },
{ status: 400 }
);
}

const parts = token.split('|');
if (parts.length !== 6) {
return NextResponse.json({ success: false, message: 'BOLETO INVÁLIDO' }, { status: 400 });
}
const supabase = await createClient();
let boletoEncontrado: {
id: string;
rutaId?: string;
pasajeroId?: string | null;
pasajeroNombre?: string | null;
pasajeroCedula?: string | null;
asiento: number | string;
estado: string;
codigoQr?: string | null;
abordadoAt?: string | null;
} | null = null;

const [boletoId, tokenBusId, tokenFecha, tokenHora, tokenAsiento, receivedHash] = parts;
const secret = process.env.QR_SECRET || 'secret_por_defecto';
// Caso 1: Token con firma HMAC (6 partes separadas por "|")
const parts = rawToken.split('|');
if (parts.length === 6) {
const [boletoId, tokenBusId, tokenFecha, tokenHora, tokenAsiento, receivedHash] = parts;
const secret = process.env.QR_SECRET || 'secret_por_defecto';

// Comparación timing-safe del HMAC para evitar ataques de temporización
const rawData = `${boletoId}|${tokenBusId}|${tokenFecha}|${tokenHora}|${tokenAsiento}`;
const calculatedHash = crypto.createHmac('sha256', secret).update(rawData).digest('hex');
const rawData = `${boletoId}|${tokenBusId}|${tokenFecha}|${tokenHora}|${tokenAsiento}`;
const calculatedHash = crypto.createHmac('sha256', secret).update(rawData).digest('hex');

const hmacMatch = crypto.timingSafeEqual(
Buffer.from(receivedHash, 'hex'),
Buffer.from(calculatedHash, 'hex')
);
const recBuf = Buffer.from(receivedHash, 'hex');
const calcBuf = Buffer.from(calculatedHash, 'hex');

if (recBuf.length !== calcBuf.length || !crypto.timingSafeEqual(recBuf, calcBuf)) {
return NextResponse.json(
{ success: false, message: 'BOLETO INVÁLIDO (Firma criptográfica incorrecta)' },
{ status: 400 }
);
}

if (!hmacMatch) {
return NextResponse.json({ success: false, message: 'BOLETO INVÁLIDO (Firma incorrecta)' }, { status: 400 });
const { data } = await supabase
.from('Boleto')
.select('*')
.eq('id', boletoId)
.maybeSingle();

boletoEncontrado = data;
} else {
// Caso 2: Código directo de boleto (ej: ECU-BOL-... o bol-... o UUID de codigoQr)
const { data: porCodigoQr } = await supabase
.from('Boleto')
.select('*')
.ilike('codigoQr', rawToken)
.maybeSingle();

if (porCodigoQr) {
boletoEncontrado = porCodigoQr;
} else {
const { data: porId } = await supabase
.from('Boleto')
.select('*')
.ilike('id', rawToken)
.maybeSingle();
boletoEncontrado = porId;
}
}

const supabase = await createClient();
const { data: boleto, error: errorBoleto } = await supabase
.from('Boleto')
.select(`
id,
asiento,
estado,
abordadoAt,
Ruta (
busId,
fecha
)
`)
.eq('id', boletoId)
.single();

if (errorBoleto || !boleto) {
return NextResponse.json({ success: false, message: 'BOLETO INVÁLIDO (No encontrado en base de datos)' }, { status: 404 });
if (!boletoEncontrado) {
return NextResponse.json(
{ success: false, message: 'BOLETO NO ENCONTRADO EN LA BASE DE DATOS' },
{ status: 404 }
);
}

const estadoNorm = (boletoEncontrado.estado || '').toUpperCase();

if (estadoNorm === 'EMBARCADO' || estadoNorm === 'ABORDADO') {
return NextResponse.json(
{
success: false,
statusType: 'YA_USADO',
message: 'ESTE BOLETO YA FUE UTILIZADO PARA ABORDAR',
boleto: boletoEncontrado,
},
{ status: 200 }
);
}

if (boleto.estado === 'EMBARCADO') {
return NextResponse.json({
success: false,
statusType: 'YA_USADO',
message: 'YA FUE USADO'
}, { status: 200 });
if (estadoNorm === 'PENDIENTE_APROBACION') {
return NextResponse.json(
{
success: false,
message: 'PAGO PENDIENTE DE APROBACIÓN EN VENTANILLA',
boleto: boletoEncontrado,
},
{ status: 400 }
);
}

const estadoNorm = (boleto.estado || '').toUpperCase();
if (
estadoNorm !== 'COMPLETADO' &&
estadoNorm !== 'CONFIRMADO' &&
estadoNorm !== 'PAGADO' &&
estadoNorm !== 'EMITIDO'
) {
return NextResponse.json({ success: false, message: 'BOLETO INVÁLIDO (Estado no apto)' }, { status: 400 });
if (estadoNorm === 'RECHAZADO' || estadoNorm === 'CANCELADO') {
return NextResponse.json(
{
success: false,
message: `BOLETO NO VÁLIDO (Estado: ${estadoNorm})`,
boleto: boletoEncontrado,
},
{ status: 400 }
);
}

const ahoraIso = new Date().toISOString();
const { error: updateError } = await supabase
const { data: actualizado, error: updateError } = await supabase
.from('Boleto')
.update({ estado: 'EMBARCADO', abordadoAt: ahoraIso })
.eq('id', boletoId);
.eq('id', boletoEncontrado.id)
.select('*')
.maybeSingle();

if (updateError) {
return NextResponse.json({ success: false, message: 'Error al actualizar el estado del boleto' }, { status: 500 });
return NextResponse.json(
{ success: false, message: 'Error al registrar el abordaje del boleto' },
{ status: 500 }
);
}

return NextResponse.json({
success: true,
statusType: 'ACCESO_PERMITIDO',
message: 'ACCESO PERMITIDO – EMBARCADO',
boleto: { id: boletoId, asiento: boleto.asiento, abordadoAt: ahoraIso }
}, { status: 200 });
const boletoFinal = actualizado || {
...boletoEncontrado,
estado: 'EMBARCADO',
abordadoAt: ahoraIso,
};

return NextResponse.json(
{
success: true,
statusType: 'ACCESO_PERMITIDO',
message: 'ACCESO PERMITIDO – PASAJERO EMBARCADO',
boleto: boletoFinal,
},
{ status: 200 }
);
} catch {
return NextResponse.json({ success: false, message: 'Error interno en el servidor de verificación' }, { status: 500 });
return NextResponse.json(
{ success: false, message: 'Error interno en el servidor de verificación' },
{ status: 500 }
);
}
}
}
23 changes: 23 additions & 0 deletions src/app/busqueda/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,29 @@ function BusquedaContent() {
}
};

// Sincronización en tiempo real de asientos ocupados cada 3 segundos mientras el modal está abierto
useEffect(() => {
if (!selectedFrecuencia || !selectedRuta || !selectedOrigenId || !selectedDestinoId) return;

const timer = setInterval(async () => {
try {
const ocupadosRes = await dataService.fetchAsientosOcupadosEnTramo(
selectedRuta.id,
selectedOrigenId,
selectedDestinoId
);
if (ocupadosRes.data) {
setOccupiedSeats(ocupadosRes.data);
setSelectedSeat((curr) => (curr && ocupadosRes.data?.includes(curr) ? null : curr));
}
} catch {
// Ignorar fallos de red silenciosos en polling
}
}, 3000);

return () => clearInterval(timer);
}, [selectedFrecuencia, selectedRuta, selectedOrigenId, selectedDestinoId]);

const handleCambioOrigen = (nuevoOrigenId: string) => {
setSelectedOrigenId(nuevoOrigenId);
if (selectedFrecuencia && selectedRuta) {
Expand Down
Loading
Loading