5.5 - Precomputing the Order Amount

This commit is contained in:
Adam Wathan
2016-11-18 18:26:56 -05:00
parent 45104cd59b
commit 510a60fcd3
4 changed files with 8 additions and 9 deletions

View File

@@ -69,7 +69,7 @@ class Concert extends Model
public function createOrder($email, $tickets) public function createOrder($email, $tickets)
{ {
return Order::forTickets($tickets, $email); return Order::forTickets($tickets, $email, $tickets->sum('price'));
} }
public function addTickets($quantity) public function addTickets($quantity)

View File

@@ -29,15 +29,14 @@ class ConcertOrdersController extends Controller
]); ]);
try { try {
// Find some tickets // Find some tickets
$tickets = $concert->findTickets(request('ticket_quantity')); $tickets = $concert->findTickets(request('ticket_quantity'));
// Charge the customer for the tickets // Charge the customer for the tickets
$this->paymentGateway->charge(request('ticket_quantity') * $concert->ticket_price, request('payment_token')); $this->paymentGateway->charge($tickets->sum('price'), request('payment_token'));
// Create an order for those tickets // Create an order for those tickets
$order = Order::forTickets($tickets, request('email')); $order = Order::forTickets($tickets, request('email'), $tickets->sum('price'));
return response()->json($order, 201); return response()->json($order, 201);

View File

@@ -8,11 +8,11 @@ class Order extends Model
{ {
protected $guarded = []; protected $guarded = [];
public static function forTickets($tickets, $email) public static function forTickets($tickets, $email, $amount)
{ {
$order = self::create([ $order = self::create([
'email' => $email, 'email' => $email,
'amount' => $tickets->sum('price'), 'amount' => $amount,
]); ]);
foreach ($tickets as $ticket) { foreach ($tickets as $ticket) {

View File

@@ -11,12 +11,12 @@ class OrderTest extends TestCase
use DatabaseMigrations; use DatabaseMigrations;
/** @test */ /** @test */
function creating_an_order_from_tickets_and_email() function creating_an_order_from_tickets_email_and_amount()
{ {
$concert = factory(Concert::class)->create(['ticket_price' => 1200])->addTickets(5); $concert = factory(Concert::class)->create()->addTickets(5);
$this->assertEquals(5, $concert->ticketsRemaining()); $this->assertEquals(5, $concert->ticketsRemaining());
$order = Order::forTickets($concert->findTickets(3), 'john@example.com'); $order = Order::forTickets($concert->findTickets(3), 'john@example.com', 3600);
$this->assertEquals('john@example.com', $order->email); $this->assertEquals('john@example.com', $order->email);
$this->assertEquals(3, $order->ticketQuantity()); $this->assertEquals(3, $order->ticketQuantity());