diff --git a/src/Invoice.php b/src/Invoice.php index cf09d993..2c3fd6ea 100644 --- a/src/Invoice.php +++ b/src/Invoice.php @@ -216,7 +216,7 @@ public function discounts() public function discountFor(Discount $discount) { if (! is_null($discountAmount = $this->rawDiscountFor($discount))) { - return $this->formatAmount($discountAmount->amount); + return $this->formatAmount($discountAmount); } } @@ -228,14 +228,15 @@ public function discountFor(Discount $discount) */ public function rawDiscountFor(Discount $discount) { - return Collection::make($this->invoice->total_discount_amounts) + return optional(Collection::make($this->invoice->total_discount_amounts) ->first(function ($discountAmount) use ($discount) { if (is_string($discountAmount->discount)) { return $discountAmount->discount === $discount->id; } else { return $discountAmount->discount->id === $discount->id; } - }); + })) + ->amount; } /** diff --git a/tests/Unit/InvoiceTest.php b/tests/Unit/InvoiceTest.php index 91362070..e2b24970 100644 --- a/tests/Unit/InvoiceTest.php +++ b/tests/Unit/InvoiceTest.php @@ -4,14 +4,14 @@ use Carbon\Carbon; use Carbon\CarbonTimeZone; +use Laravel\Cashier\Discount; use Laravel\Cashier\Invoice; use Laravel\Cashier\Tests\Fixtures\User; use Laravel\Cashier\Tests\TestCase; use Mockery as m; use stdClass; -use Stripe\Coupon; use Stripe\Customer as StripeCustomer; -use Stripe\Discount; +use Stripe\Discount as StripeDiscount; use Stripe\Invoice as StripeInvoice; class InvoiceTest extends TestCase @@ -189,19 +189,18 @@ public function test_it_can_return_its_raw_starting_balance() public function test_it_can_determine_if_it_has_a_discount_applied() { - $coupon = new Coupon(); - $coupon->amount_off = 50; - - $discount = new Discount(); - $discount->coupon = $coupon; - $discountAmount = new stdClass(); $discountAmount->amount = 50; + $discountAmount->discount = $discount = new StripeDiscount('foo'); + + $otherDiscountAmount = new stdClass(); + $otherDiscountAmount->amount = 100; + $otherDiscountAmount->discount = $otherDiscount = new StripeDiscount('bar'); $stripeInvoice = new StripeInvoice(); - $stripeInvoice->total_discount_amounts = [$discountAmount]; + $stripeInvoice->total_discount_amounts = [$discountAmount, $otherDiscountAmount]; $stripeInvoice->customer = 'foo'; - $stripeInvoice->discounts = [$discount]; + $stripeInvoice->discounts = [$discount, $otherDiscount]; $user = new User(); $user->stripe_id = 'foo'; @@ -209,7 +208,9 @@ public function test_it_can_determine_if_it_has_a_discount_applied() $invoice = new Invoice($user, $stripeInvoice); $this->assertTrue($invoice->hasDiscount()); - $this->assertSame(50, $invoice->rawDiscount()); + $this->assertSame(150, $invoice->rawDiscount()); + $this->assertSame(50, $invoice->rawDiscountFor(new Discount($discount))); + $this->assertNull($invoice->rawDiscountFor(new Discount(new StripeDiscount('baz')))); } public function test_it_can_return_its_tax()