Skip to content
Merged
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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,6 @@ Thumbs.db
/logs/
/cache/
/docs/coverage/

.env.testing
.phpunit.result.cache
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Fixed

- Corregir lógica de fechas en vista v_ocupacion_diaria para contar reservas durante toda su estancia (rango fecha_entrada a fecha_salida) en lugar de solo en la fecha de entrada, respetando el agrupamiento macro por tipo de espacio.

## [1.0.0] - 2024-05-15

### Added
Expand Down
31 changes: 31 additions & 0 deletions database/migrations/002_fix_v_ocupacion_diaria.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
-- Migración: Corrección de bug en vista v_ocupacion_diaria
-- Problema: El JOIN original solo contaba reservas en su fecha_entrada exacta.
-- Solución: Evaluar si la fecha del calendario cae en el rango [fecha_entrada, fecha_salida).
-- Nota: Se respeta el agrupamiento original por tipo_espacio para análisis macro.

DROP VIEW IF EXISTS v_ocupacion_diaria;

CREATE VIEW v_ocupacion_diaria AS
WITH RECURSIVE calendario AS (
SELECT DATE_SUB(CURDATE(), INTERVAL 365 DAY) AS fecha
UNION ALL
SELECT DATE_ADD(fecha, INTERVAL 1 DAY)
FROM calendario
WHERE fecha < DATE_ADD(CURDATE(), INTERVAL 365 DAY)
),
tipos_espacios AS (
SELECT DISTINCT tipo AS tipo_espacio FROM espacios
)
SELECT
c.fecha,
t.tipo_espacio,
COALESCE(COUNT(r.id), 0) AS reservas_activas,
COALESCE(SUM(r.precio_total), 0) AS revenue_diario
FROM calendario c
CROSS JOIN tipos_espacios t
LEFT JOIN espacios e ON e.tipo = t.tipo_espacio
LEFT JOIN reservas r ON r.espacio_id = e.id
AND c.fecha >= r.fecha_entrada
AND c.fecha < r.fecha_salida
AND r.estado = 'confirmada'
GROUP BY c.fecha, t.tipo_espacio;
4 changes: 1 addition & 3 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
version: '3.8'

services:
app:
build:
Expand Down Expand Up @@ -31,7 +29,7 @@ services:
MARIADB_ROOT_PASSWORD: secret
MARIADB_DATABASE: salitre_db
ports:
- "3306:3306"
- "3308:3306"
volumes:
- db_data:/var/lib/mysql
# Autoejecutar setup.sql al crear la DB por primera vez
Expand Down
100 changes: 100 additions & 0 deletions tests/Integration/VistaOcupacionDiariaTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<?php

declare(strict_types=1);

namespace Tests\Integration;

use PHPUnit\Framework\TestCase;
use PDO;
use DateTimeImmutable;

final class VistaOcupacionDiariaTest extends TestCase
{
private static PDO $pdo;

public static function setUpBeforeClass(): void
{
$host = getenv('DB_HOST') ?: 'db';
$port = getenv('DB_PORT') ?: '3306';
$dbname = getenv('DB_NAME') ?: 'salitre_db';
$user = getenv('DB_USER') ?: 'root';
$pass = getenv('DB_PASS') ?: 'secret';

self::$pdo = new PDO(
"mysql:host={$host};port={$port};dbname={$dbname};charset=utf8mb4",
$user,
$pass,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]
);
}

public function testReservaAbarcaTodaSuEstanciaPorTipoEspacio(): void
{
$tipoEspacio = 'villa';
$hoy = new DateTimeImmutable();
$fechaEntrada = $hoy->format('Y-m-d');
$fechaSalida = $hoy->modify('+3 days')->format('Y-m-d');
$precioTotal = 5000.00;

// Se obtiene línea base (Delta approach para ignorar datos seed existentes)
$stmtBase = self::$pdo->prepare(
'SELECT reservas_activas, revenue_diario FROM v_ocupacion_diaria
WHERE tipo_espacio = :tipo AND fecha = :fecha'
);
$stmtBase->execute(['tipo' => $tipoEspacio, 'fecha' => $fechaEntrada]);
$base = $stmtBase->fetch() ?: ['reservas_activas' => 0, 'revenue_diario' => 0];

// Se crean los datos de prueba
self::$pdo->beginTransaction();
try {
$stmtEsp = self::$pdo->prepare(
'INSERT INTO espacios (nombre, slug, tipo, precio_noche, capacidad)
VALUES (:nombre, :slug, :tipo, :precio, 1)'
);
$stmtEsp->execute([
'nombre' => 'Villa Test Ocupacion',
'slug' => 'villa-test-ocupacion-' . uniqid(),
'tipo' => $tipoEspacio,
'precio' => 1000.00
]);
$espacioId = (int) self::$pdo->lastInsertId();

$stmtRes = self::$pdo->prepare(
'INSERT INTO reservas (cliente_id, espacio_id, fecha_entrada, fecha_salida, noches, precio_total, estado)
VALUES (1, :espacio, :entrada, :salida, 3, :precio, "confirmada")'
);
$stmtRes->execute([
'espacio' => $espacioId,
'entrada' => $fechaEntrada,
'salida' => $fechaSalida,
'precio' => $precioTotal
]);

// Se valida día de entrada (Debe sumar +1 reserva y +precio a la base)
$stmtBase->execute(['tipo' => $tipoEspacio, 'fecha' => $fechaEntrada]);
$dia1 = $stmtBase->fetch();
$this->assertEquals($base['reservas_activas'] + 1, $dia1['reservas_activas'], 'Día de entrada debe sumar 1 reserva');
$this->assertEquals($base['revenue_diario'] + $precioTotal, $dia1['revenue_diario'], 'Día de entrada debe sumar revenue');

// Se valida día intermedio (La reserva sigue activa)
$fechaIntermedia = $hoy->modify('+1 day')->format('Y-m-d');
$stmtBase->execute(['tipo' => $tipoEspacio, 'fecha' => $fechaIntermedia]);
$dia2 = $stmtBase->fetch();
$this->assertEquals($base['reservas_activas'] + 1, $dia2['reservas_activas'], 'Día intermedio debe mantener la reserva activa');

// Se valida día de salida (Fecha exclusiva, la reserva ya no cuenta)
$stmtBase->execute(['tipo' => $tipoEspacio, 'fecha' => $fechaSalida]);
$diaSalida = $stmtBase->fetch();
$this->assertEquals($base['reservas_activas'], $diaSalida['reservas_activas'], 'Día de salida no debe contar la reserva');

self::$pdo->rollBack();
} catch (\Exception $e) {
self::$pdo->rollBack();
throw $e;
}
}
}
Loading