GiftCardService.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace Longyi\Gift\Services;
  3. use Webkul\Checkout\Facades\Cart;
  4. use Longyi\Gift\Models\GiftCards;
  5. class GiftCardService
  6. {
  7. /**
  8. * 激活礼品卡
  9. */
  10. public function activate(string $code, ?int $customerId = null): void
  11. {
  12. $customerId = $customerId ?? auth()->user()?->id;
  13. if (! $customerId) {
  14. throw new \Exception('Customer not authenticated.');
  15. }
  16. $giftCard = GiftCards::where('giftcard_number', $code)
  17. ->where('customer_id', $customerId)
  18. ->first();
  19. if (! $giftCard) {
  20. throw new \Exception('Gift card not found.');
  21. }
  22. $cart = Cart::getCart();
  23. if (!empty($cart->giftcard_amount)) {
  24. throw new \Exception(
  25. 'The shopping cart has been paid with a gift card.'
  26. );
  27. }
  28. GiftCards::setGiftCardCode($giftCard);
  29. Cart::collectTotals();
  30. }
  31. /**
  32. * 删除礼品卡
  33. */
  34. public function remove(?int $customerId = null): void
  35. {
  36. $customerId = $customerId ?? auth()->user()?->id;
  37. $cart = Cart::getCart();
  38. GiftCards::removeGiftCardCode();
  39. Cart::collectTotals();
  40. if ($cart->giftcard_number && $customerId) {
  41. $giftCard = GiftCards::where(
  42. 'giftcard_number',
  43. $cart->giftcard_number
  44. )
  45. ->where('customer_id', $customerId)
  46. ->first();
  47. if ($giftCard) {
  48. $giftCard->used_giftcard_amount = 0;
  49. $giftCard->remaining_giftcard_amount = $giftCard->giftcard_amount;
  50. $giftCard->save();
  51. }
  52. }
  53. }
  54. }