MemberDiscountService.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. namespace Longyi\Member\Services;
  3. use Webkul\Checkout\Facades\Cart;
  4. class MemberDiscountService
  5. {
  6. /**
  7. * Member discount amount.
  8. */
  9. protected const MEMBER_DISCOUNT_AMOUNT = 19.9;
  10. /**
  11. * Apply member discount to cart.
  12. */
  13. public function apply(): void
  14. {
  15. $cart = Cart::getCart();
  16. if (! $cart) {
  17. throw new \Exception('Shopping cart not found.');
  18. }
  19. if ($cart->vip_plus_amount && $cart->vip_plus_amount > 0) {
  20. throw new \Exception('Member discount has already been applied.');
  21. }
  22. $discountAmount = core()->convertPrice(self::MEMBER_DISCOUNT_AMOUNT);
  23. $cart->vip_plus_amount = $discountAmount;
  24. $cart->base_vip_plus_amount = core()->convertToBasePrice($discountAmount);
  25. $cart->save();
  26. Cart::collectTotals();
  27. }
  28. /**
  29. * Remove member discount from cart.
  30. */
  31. public function remove(): void
  32. {
  33. $cart = Cart::getCart();
  34. if (! $cart || ! $cart->vip_plus_amount || $cart->vip_plus_amount <= 0) {
  35. return;
  36. }
  37. $cart->vip_plus_amount = null;
  38. $cart->base_vip_plus_amount = null;
  39. $cart->save();
  40. Cart::collectTotals();
  41. }
  42. }