From a771a0a2c2f8700637a87833a6fc4cddb42e13b9 Mon Sep 17 00:00:00 2001 From: Jakub Theimer <5587309+theimerj@users.noreply.github.com> Date: Fri, 8 Sep 2023 13:23:55 +0200 Subject: [PATCH] test that discounts can be applied with multiple calculate method calls on cart --- .../Unit/DiscountTypes/AmountOffTest.php | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/packages/core/tests/Unit/DiscountTypes/AmountOffTest.php b/packages/core/tests/Unit/DiscountTypes/AmountOffTest.php index 08d61ae541..63490b9e70 100644 --- a/packages/core/tests/Unit/DiscountTypes/AmountOffTest.php +++ b/packages/core/tests/Unit/DiscountTypes/AmountOffTest.php @@ -4,6 +4,7 @@ use Illuminate\Foundation\Testing\RefreshDatabase; use Lunar\DiscountTypes\AmountOff; +use Lunar\Facades\CartSession; use Lunar\Models\Brand; use Lunar\Models\Cart; use Lunar\Models\Channel; @@ -1221,4 +1222,78 @@ public function cannot_apply_discount_with_max_user_uses() $this->assertEquals(2400, $cart->total->value); $this->assertEquals(2000, $cart->subTotal->value); } + + /** + * @test + */ + public function can_apply_discount_dynamically() + { + $currency = Currency::getDefault(); + + $customerGroup = CustomerGroup::getDefault(); + + $channel = Channel::getDefault(); + + $cart = Cart::factory()->create([ + 'currency_id' => $currency->id, + 'channel_id' => $channel->id, + 'coupon_code' => '10OFF', + ]); + + $purchasableA = ProductVariant::factory()->create(); + + Price::factory()->create([ + 'price' => 1000, // £10 + 'tier' => 1, + 'currency_id' => $currency->id, + 'priceable_type' => get_class($purchasableA), + 'priceable_id' => $purchasableA->id, + ]); + + $cart->lines()->create([ + 'purchasable_type' => get_class($purchasableA), + 'purchasable_id' => $purchasableA->id, + 'quantity' => 2, + ]); + + $discount = Discount::factory()->create([ + 'type' => AmountOff::class, + 'name' => 'Test Coupon', + 'coupon' => '10OFF', + 'data' => [ + 'fixed_value' => true, + 'fixed_values' => [ + 'GBP' => 10.5, + ], + ], + ]); + + $discount->customerGroups()->sync([ + $customerGroup->id => [ + 'enabled' => true, + 'starts_at' => now(), + ], + ]); + + $discount->channels()->sync([ + $channel->id => [ + 'enabled' => true, + 'starts_at' => now()->subHour(), + ], + ]); + + // Calculate method called for the first time + CartSession::use($cart); + + // Calculate method called for the second time + $cart = CartSession::current(); + + // Calculate method called for the third time + $cart = $cart->calculate(); + + $this->assertEquals(1050, $cart->discountTotal->value); + $this->assertEquals(1140, $cart->total->value); + $this->assertEquals(190, $cart->taxTotal->value); + $this->assertCount(1, $cart->discounts); + } }