diff --git a/app/Concert.php b/app/Concert.php index 31041e7..1ac6f44 100644 --- a/app/Concert.php +++ b/app/Concert.php @@ -58,7 +58,9 @@ class Concert extends Model public function reserveTickets($quantity) { - return $this->findTickets($quantity); + return $this->findTickets($quantity)->each(function ($ticket) { + $ticket->reserve(); + }); } public function findTickets($quantity) diff --git a/app/Http/Controllers/ConcertOrdersController.php b/app/Http/Controllers/ConcertOrdersController.php index baa3452..02d2832 100644 --- a/app/Http/Controllers/ConcertOrdersController.php +++ b/app/Http/Controllers/ConcertOrdersController.php @@ -31,7 +31,7 @@ class ConcertOrdersController extends Controller try { // Find some tickets - $tickets = $concert->findTickets(request('ticket_quantity')); + $tickets = $concert->reserveTickets(request('ticket_quantity')); $reservation = new Reservation($tickets); // Charge the customer for the tickets diff --git a/app/Ticket.php b/app/Ticket.php index 5e2f52b..e62d4e7 100644 --- a/app/Ticket.php +++ b/app/Ticket.php @@ -11,7 +11,7 @@ class Ticket extends Model public function scopeAvailable($query) { - return $query->whereNull('order_id'); + return $query->whereNull('order_id')->whereNull('reserved_at'); } public function reserve() diff --git a/tests/unit/ConcertTest.php b/tests/unit/ConcertTest.php index c717649..cd6d210 100644 --- a/tests/unit/ConcertTest.php +++ b/tests/unit/ConcertTest.php @@ -129,4 +129,36 @@ class ConcertTest extends TestCase $this->assertCount(2, $reservedTickets); $this->assertEquals(1, $concert->ticketsRemaining()); } + + /** @test */ + function cannot_reserve_tickets_that_have_already_been_purchased() + { + $concert = factory(Concert::class)->create()->addTickets(3); + $concert->orderTickets('jane@example.com', 2); + + try { + $concert->reserveTickets(2); + } catch (NotEnoughTicketsException $e) { + $this->assertEquals(1, $concert->ticketsRemaining()); + return; + } + + $this->fail("Reserving tickets succeeded even though the tickets were already sold."); + } + + /** @test */ + function cannot_reserve_tickets_that_have_already_been_reserved() + { + $concert = factory(Concert::class)->create()->addTickets(3); + $concert->reserveTickets(2); + + try { + $concert->reserveTickets(2); + } catch (NotEnoughTicketsException $e) { + $this->assertEquals(1, $concert->ticketsRemaining()); + return; + } + + $this->fail("Reserving tickets succeeded even though the tickets were already reserved."); + } }