Skip to content

Commit

Permalink
Merge pull request #22 from Safemood/21-bug-limited-usage-coupon-appl…
Browse files Browse the repository at this point in the history
…ied-multiple-times-despite-usage-limit-of-1

Bug Fix: Ensure Limited Usage Coupon is Applied Only Once
  • Loading branch information
Safemood committed Mar 31, 2024
2 parents 2047e95 + c094582 commit 7165873
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/CouponManager.php
Expand Up @@ -145,6 +145,8 @@ public function verify(string $code, int|string|null $userId = null): bool
}

if (! $this->checkUsageLimit($coupon)) {
$this->remove($code);

return false;
}

Expand Down
48 changes: 48 additions & 0 deletions tests/DiscountifyTest.php
Expand Up @@ -534,3 +534,51 @@
expect($isInTheDate)->toBeFalse();
expect($total)->toBe(floatval(90)); // Total without any discount applied
});

it('applies limited usage coupon only once', function () {

Coupon::add([
'code' => 'LIMITED50',
'discount' => 50,
'usageLimit' => 1, // Limited to 1 uses
'startDate' => now(),
'endDate' => now()->addWeek(),
]);

$items = [
[
'id' => 1,
'product_id' => 1,
'product_name' => 'Product 1',
'quantity' => 5,
'price' => 10,
],
[
'id' => 2,
'product_id' => 2,
'product_name' => 'Product 2',
'quantity' => 2,
'price' => 25,
],
];

$discountedTotal1 = DiscountifyFacade::setItems($items)
->applyCoupon('LIMITED50')
->total();

$appleied1 = DiscountifyFacade::coupons()->appliedCoupons();

$discountedTotal2 = DiscountifyFacade::setItems($items)
->applyCoupon('LIMITED50')
->total();

$appleied2 = DiscountifyFacade::coupons()->appliedCoupons();

expect($discountedTotal1)->toBe(floatval(50));
expect($appleied1)->not->toBeEmpty();
expect($appleied1[0]['code'])->toEqual('LIMITED50');

expect($discountedTotal2)->toBe(floatval(100)); // without the discount
expect($appleied2)->toBeEmpty();

});

0 comments on commit 7165873

Please sign in to comment.