| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245 |
- <?php
- namespace Longyi\Gift\Http\Controllers\Shop;
- use Illuminate\Http\JsonResponse;
- use Illuminate\Http\Request;
- use Illuminate\Http\Resources\Json\JsonResource;
- use Illuminate\Http\Response;
- use Longyi\RewardPoints\Repositories\RewardPointRepository;
- use Webkul\Checkout\Facades\Cart;
- use Webkul\Shop\Http\Controllers\Controller;
- use Longyi\Gift\Repositories\GiftCardsRepository;
- use Longyi\Gift\Models\GiftCards;
- use Longyi\Gift\Http\Resources\CustomCartResource;
- use Longyi\RewardPoints\Helpers\ApiResponse;
- class GiftController extends Controller
- {
- public function __construct(
- protected GiftCardsRepository $giftCardRepository,
- protected GiftCards $giftCardsModel,
- protected RewardPointRepository $rewardPointRepository
- ) {
- }
- public function index()
- {
- echo 111;exit;
- return view('giftcard::shop.index');
- }
- public function lists(): JsonResponse
- {
- $customerId = auth()->user()->id;
- // 获取用户拥有的所有礼品卡
- $userGiftCards = GiftCards::where('customer_id', $customerId)
- ->where('giftcard_status', 1)
- ->get()
- ->keyBy('channel');
- $gifts = $this->giftCardsModel->giftcards();
- foreach ($gifts as &$gift) {
- $channel = $gift['channel'];
- if (isset($userGiftCards[$channel])) {
- $gift['status'] = true;
- } else {
- $gift['status'] = false;
- }
- }
- return ApiResponse::success([
- 'lists' => $gifts,
- 'myPoints' => $this->rewardPointRepository->getCustomerPoints($customerId)
- ]);
- }
- public function add(Request $request): JsonResponse
- {
- $id = $request->input('id');
- if (!$id) {
- return ApiResponse::error('Gift card not found');
- }
- $customerId = auth()->user()->id;
- try {
- $this->giftCardsModel->add($id, $customerId);
- } catch (\Exception $e) {
- return ApiResponse::error($e->getMessage());
- }
- return ApiResponse::success('Gift card added successfully');
- }
- /**
- * Get customer's gift cards list (with pagination)
- */
- public function getCustomerGiftCards(Request $request): JsonResponse
- {
- try {
- $customerId = auth()->user()->id;
- $perPage = (int) $request->input('per_page', 10);
- $paginator = GiftCards::where('customer_id', $customerId)
- ->where('remaining_giftcard_amount', '>', 0)
- ->where('expirationdate', '>=', now())
- ->orderBy('created_at', 'desc')
- ->paginate($perPage);
- $data = $paginator->map(function ($giftCard) {
- return [
- 'id' => $giftCard->id,
- 'giftcard_number' => $giftCard->giftcard_number,
- 'giftcard_amount' => $giftCard->giftcard_amount,
- 'remaining_giftcard_amount' => $giftCard->remaining_giftcard_amount,
- 'formatted_remaining_giftcard_amount' => core()->formatPrice(core()->convertPrice($giftCard->remaining_giftcard_amount)),
- 'used_giftcard_amount' => $giftCard->used_giftcard_amount,
- 'expirationdate' => $giftCard->expirationdate->format('Y-m-d'),
- 'giftcard_status' => $giftCard->giftcard_status
- ];
- });
- return ApiResponse::paginated($data, $paginator);
- } catch (\Exception $e) {
- return ApiResponse::error($e->getMessage());
- }
- }
- /**
- * Activate Giftcard.
- */
- public function activateGiftCard(Request $request)
- {
- $customerId = auth()->user()->id;
- try {
- $validatedData = $this->validate($request, [
- 'giftcard_number' => 'required',
- ]);
- $giftCard = GiftCards::where('giftcard_number', $validatedData['giftcard_number'])
- ->where('customer_id', $customerId)->first();
- $cart = Cart::getCart();
- if (!$giftCard) {
- return ApiResponse::error('Coupon not found.');
- }
- $remainingGiftcardAmount = core()->convertPrice($giftCard->remaining_giftcard_amount);
- if ($remainingGiftcardAmount <= 0) {
- return ApiResponse::error('Gift card already used.');
- }
- if (!empty($cart->giftcard_amount)) {
- return ApiResponse::error('The shopping cart has been paid with a gift card.');
- }
- $cartTotal = $cart->grand_total;
- $remainingAmount = $remainingGiftcardAmount - $cartTotal;
- // Apply the gift card to the cart
- GiftCards::setGiftCardCode($giftCard);
- Cart::collectTotals();
- // Gift card amount becomes zero as it's fully used
- return ApiResponse::success([
- 'remaining_amount' => $remainingAmount >= 0 ? $remainingAmount : 0,
- 'giftcard_number' => $giftCard->giftcard_number,
- ]);
- } catch (\Exception $e) {
- return ApiResponse::error($e->getMessage());
- }
- }
- /**
- * Remove applied Giftcard from the cart.
- */
- public function destroyGiftCard()
- {
- // Get the cart instance
- $cart = Cart::getCart();
- // Remove gift card related fields from the cart
- GiftCards::removeGiftCardCode();
- Cart::collectTotals();
- // If a gift card was applied, update GiftCardBalance accordingly
- if ($cart->giftcard_number) {
- $giftCards = GiftCards::where('giftcard_number', $cart->giftcard_number)
- ->where('customer_id', auth()->user()->id)
- ->first();
- if ($giftCards) {
- // Reset used and remaining amounts
- $giftCards->used_giftcard_amount = 0;
- $giftCards->remaining_giftcard_amount = $giftCards->giftcard_amount;
- $giftCards->save();
- }
- }
- // Return response with updated cart data
- return ApiResponse::success([
- 'data' => new CustomCartResource(Cart::getCart())
- ], trans('gift::app.giftcard.remove'));
- }
- /**
- * Get the gift card that expires soonest (within specified days)
- */
- public function getExpiringSoonGiftCard(int $days = 7): ?GiftCards
- {
- try {
- $customerId = auth()->user()->id;
- $expiringDate = now()->addDays($days);
- $giftCard = GiftCards::where('customer_id', $customerId)
- ->where('remaining_giftcard_amount', '>', 0)
- ->where('expirationdate', '>=', now())
- ->where('expirationdate', '<=', $expiringDate)
- ->orderBy('expirationdate', 'asc')
- ->first();
- return $giftCard;
- } catch (\Exception $e) {
- return null;
- }
- }
- /**
- * Automatically apply the soonest expiring gift card to cart
- */
- public function autoApplyExpiringGiftCard(): JsonResponse
- {
- try {
- if (!auth()->check()) {
- return response()->json([
- 'success' => false,
- 'message' => 'User not authenticated',
- ], Response::HTTP_UNAUTHORIZED);
- }
- $cart = Cart::getCart();
- if (!$cart) {
- return response()->json([
- 'success' => false,
- 'message' => 'Cart not found',
- ], Response::HTTP_NOT_FOUND);
- }
- if (!empty($cart->giftcard_number)) {
- return response()->json([
- 'success' => false,
- 'message' => 'A gift card is already applied to the cart',
- 'applied' => true,
- ], Response::HTTP_OK);
- }
- $expiringGiftCard = $this->getExpiringSoonGiftCard(10);
- if (!$expiringGiftCard) {
- return response()->json([
- 'success' => false,
- 'message' => 'No expiring gift cards found',
- 'applied' => false,
- ], Response::HTTP_OK);
- }
- GiftCards::setGiftCardCode($expiringGiftCard);
- Cart::collectTotals();
- return response()->json([
- 'success' => true,
- 'message' => 'Expiring gift card applied automatically',
- 'giftcard_number' => $expiringGiftCard->giftcard_number,
- 'expiration_date' => $expiringGiftCard->expirationdate->format('Y-m-d'),
- 'remaining_amount' => $expiringGiftCard->remaining_giftcard_amount,
- 'applied' => true,
- ], Response::HTTP_OK);
- } catch (\Exception $e) {
- return response()->json([
- 'success' => false,
- 'message' => 'Failed to auto-apply gift card',
- 'error' => $e->getMessage(),
- ], Response::HTTP_INTERNAL_SERVER_ERROR);
- }
- }
- }
|