| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- <?php
- namespace Longyi\Gift\Services;
- use Webkul\Checkout\Facades\Cart;
- use Longyi\Gift\Models\GiftCards;
- class GiftCardService
- {
- /**
- * 激活礼品卡
- */
- public function activate(string $code, ?int $customerId = null): void
- {
- $customerId = $customerId ?? auth()->user()?->id;
- if (! $customerId) {
- throw new \Exception('Customer not authenticated.');
- }
- $giftCard = GiftCards::where('giftcard_number', $code)
- ->where('customer_id', $customerId)
- ->first();
- if (! $giftCard) {
- throw new \Exception('Gift card not found.');
- }
- $cart = Cart::getCart();
- if (!empty($cart->giftcard_amount)) {
- throw new \Exception(
- 'The shopping cart has been paid with a gift card.'
- );
- }
- GiftCards::setGiftCardCode($giftCard);
- Cart::collectTotals();
- }
- /**
- * 删除礼品卡
- */
- public function remove(?int $customerId = null): void
- {
- $customerId = $customerId ?? auth()->user()?->id;
- $cart = Cart::getCart();
- GiftCards::removeGiftCardCode();
- Cart::collectTotals();
- if ($cart->giftcard_number && $customerId) {
- $giftCard = GiftCards::where(
- 'giftcard_number',
- $cart->giftcard_number
- )
- ->where('customer_id', $customerId)
- ->first();
- if ($giftCard) {
- $giftCard->used_giftcard_amount = 0;
- $giftCard->remaining_giftcard_amount = $giftCard->giftcard_amount;
- $giftCard->save();
- }
- }
- }
- }
|