GiftController.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. <?php
  2. namespace Longyi\Gift\Http\Controllers\Shop;
  3. use Illuminate\Http\JsonResponse;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Http\Resources\Json\JsonResource;
  6. use Illuminate\Http\Response;
  7. use Longyi\RewardPoints\Repositories\RewardPointRepository;
  8. use Webkul\Checkout\Facades\Cart;
  9. use Webkul\Shop\Http\Controllers\Controller;
  10. use Longyi\Gift\Repositories\GiftCardsRepository;
  11. use Longyi\Gift\Models\GiftCards;
  12. use Longyi\Gift\Http\Resources\CustomCartResource;
  13. use Longyi\RewardPoints\Helpers\ApiResponse;
  14. class GiftController extends Controller
  15. {
  16. public function __construct(
  17. protected GiftCardsRepository $giftCardRepository,
  18. protected GiftCards $giftCardsModel,
  19. protected RewardPointRepository $rewardPointRepository
  20. ) {
  21. }
  22. public function index()
  23. {
  24. echo 111;exit;
  25. return view('giftcard::shop.index');
  26. }
  27. public function lists(): JsonResponse
  28. {
  29. $customerId = auth()->user()->id;
  30. // 获取用户拥有的所有礼品卡
  31. $userGiftCards = GiftCards::where('customer_id', $customerId)
  32. ->where('giftcard_status', 1)
  33. ->get()
  34. ->keyBy('channel');
  35. $gifts = $this->giftCardsModel->giftcards();
  36. foreach ($gifts as &$gift) {
  37. $channel = $gift['channel'];
  38. if (isset($userGiftCards[$channel])) {
  39. $gift['status'] = true;
  40. } else {
  41. $gift['status'] = false;
  42. }
  43. }
  44. return ApiResponse::success([
  45. 'lists' => $gifts,
  46. 'myPoints' => $this->rewardPointRepository->getCustomerPoints($customerId)
  47. ]);
  48. }
  49. public function add(Request $request): JsonResponse
  50. {
  51. $id = $request->input('id');
  52. if (!$id) {
  53. return ApiResponse::error('Gift card not found');
  54. }
  55. $customerId = auth()->user()->id;
  56. try {
  57. $this->giftCardsModel->add($id, $customerId);
  58. } catch (\Exception $e) {
  59. return ApiResponse::error($e->getMessage());
  60. }
  61. return ApiResponse::success('Gift card added successfully');
  62. }
  63. /**
  64. * Get customer's gift cards list (with pagination)
  65. */
  66. public function getCustomerGiftCards(Request $request): JsonResponse
  67. {
  68. try {
  69. $customerId = auth()->user()->id;
  70. $perPage = (int) $request->input('per_page', 10);
  71. $paginator = GiftCards::where('customer_id', $customerId)
  72. ->where('remaining_giftcard_amount', '>', 0)
  73. ->where('expirationdate', '>=', now())
  74. ->orderBy('created_at', 'desc')
  75. ->paginate($perPage);
  76. $data = $paginator->map(function ($giftCard) {
  77. return [
  78. 'id' => $giftCard->id,
  79. 'giftcard_number' => $giftCard->giftcard_number,
  80. 'giftcard_amount' => $giftCard->giftcard_amount,
  81. 'remaining_giftcard_amount' => $giftCard->remaining_giftcard_amount,
  82. 'formatted_remaining_giftcard_amount' => core()->formatPrice(core()->convertPrice($giftCard->remaining_giftcard_amount)),
  83. 'used_giftcard_amount' => $giftCard->used_giftcard_amount,
  84. 'expirationdate' => $giftCard->expirationdate->format('Y-m-d'),
  85. 'giftcard_status' => $giftCard->giftcard_status
  86. ];
  87. });
  88. return ApiResponse::paginated($data, $paginator);
  89. } catch (\Exception $e) {
  90. return ApiResponse::error($e->getMessage());
  91. }
  92. }
  93. /**
  94. * Activate Giftcard.
  95. */
  96. public function activateGiftCard(Request $request)
  97. {
  98. $customerId = auth()->user()->id;
  99. try {
  100. $validatedData = $this->validate($request, [
  101. 'giftcard_number' => 'required',
  102. ]);
  103. $giftCard = GiftCards::where('giftcard_number', $validatedData['giftcard_number'])
  104. ->where('customer_id', $customerId)->first();
  105. $cart = Cart::getCart();
  106. if (!$giftCard) {
  107. return ApiResponse::error('Coupon not found.');
  108. }
  109. $remainingGiftcardAmount = core()->convertPrice($giftCard->remaining_giftcard_amount);
  110. if ($remainingGiftcardAmount <= 0) {
  111. return ApiResponse::error('Gift card already used.');
  112. }
  113. if (!empty($cart->giftcard_amount)) {
  114. return ApiResponse::error('The shopping cart has been paid with a gift card.');
  115. }
  116. $cartTotal = $cart->grand_total;
  117. $remainingAmount = $remainingGiftcardAmount - $cartTotal;
  118. // Apply the gift card to the cart
  119. GiftCards::setGiftCardCode($giftCard);
  120. Cart::collectTotals();
  121. // Gift card amount becomes zero as it's fully used
  122. return ApiResponse::success([
  123. 'remaining_amount' => $remainingAmount >= 0 ? $remainingAmount : 0,
  124. 'giftcard_number' => $giftCard->giftcard_number,
  125. ]);
  126. } catch (\Exception $e) {
  127. return ApiResponse::error($e->getMessage());
  128. }
  129. }
  130. /**
  131. * Remove applied Giftcard from the cart.
  132. */
  133. public function destroyGiftCard()
  134. {
  135. // Get the cart instance
  136. $cart = Cart::getCart();
  137. // Remove gift card related fields from the cart
  138. GiftCards::removeGiftCardCode();
  139. Cart::collectTotals();
  140. // If a gift card was applied, update GiftCardBalance accordingly
  141. if ($cart->giftcard_number) {
  142. $giftCards = GiftCards::where('giftcard_number', $cart->giftcard_number)
  143. ->where('customer_id', auth()->user()->id)
  144. ->first();
  145. if ($giftCards) {
  146. // Reset used and remaining amounts
  147. $giftCards->used_giftcard_amount = 0;
  148. $giftCards->remaining_giftcard_amount = $giftCards->giftcard_amount;
  149. $giftCards->save();
  150. }
  151. }
  152. // Return response with updated cart data
  153. return ApiResponse::success([
  154. 'data' => new CustomCartResource(Cart::getCart())
  155. ], trans('gift::app.giftcard.remove'));
  156. }
  157. /**
  158. * Get the gift card that expires soonest (within specified days)
  159. */
  160. public function getExpiringSoonGiftCard(int $days = 7): ?GiftCards
  161. {
  162. try {
  163. $customerId = auth()->user()->id;
  164. $expiringDate = now()->addDays($days);
  165. $giftCard = GiftCards::where('customer_id', $customerId)
  166. ->where('remaining_giftcard_amount', '>', 0)
  167. ->where('expirationdate', '>=', now())
  168. ->where('expirationdate', '<=', $expiringDate)
  169. ->orderBy('expirationdate', 'asc')
  170. ->first();
  171. return $giftCard;
  172. } catch (\Exception $e) {
  173. return null;
  174. }
  175. }
  176. /**
  177. * Automatically apply the soonest expiring gift card to cart
  178. */
  179. public function autoApplyExpiringGiftCard(): JsonResponse
  180. {
  181. try {
  182. if (!auth()->check()) {
  183. return response()->json([
  184. 'success' => false,
  185. 'message' => 'User not authenticated',
  186. ], Response::HTTP_UNAUTHORIZED);
  187. }
  188. $cart = Cart::getCart();
  189. if (!$cart) {
  190. return response()->json([
  191. 'success' => false,
  192. 'message' => 'Cart not found',
  193. ], Response::HTTP_NOT_FOUND);
  194. }
  195. if (!empty($cart->giftcard_number)) {
  196. return response()->json([
  197. 'success' => false,
  198. 'message' => 'A gift card is already applied to the cart',
  199. 'applied' => true,
  200. ], Response::HTTP_OK);
  201. }
  202. $expiringGiftCard = $this->getExpiringSoonGiftCard(10);
  203. if (!$expiringGiftCard) {
  204. return response()->json([
  205. 'success' => false,
  206. 'message' => 'No expiring gift cards found',
  207. 'applied' => false,
  208. ], Response::HTTP_OK);
  209. }
  210. GiftCards::setGiftCardCode($expiringGiftCard);
  211. Cart::collectTotals();
  212. return response()->json([
  213. 'success' => true,
  214. 'message' => 'Expiring gift card applied automatically',
  215. 'giftcard_number' => $expiringGiftCard->giftcard_number,
  216. 'expiration_date' => $expiringGiftCard->expirationdate->format('Y-m-d'),
  217. 'remaining_amount' => $expiringGiftCard->remaining_giftcard_amount,
  218. 'applied' => true,
  219. ], Response::HTTP_OK);
  220. } catch (\Exception $e) {
  221. return response()->json([
  222. 'success' => false,
  223. 'message' => 'Failed to auto-apply gift card',
  224. 'error' => $e->getMessage(),
  225. ], Response::HTTP_INTERNAL_SERVER_ERROR);
  226. }
  227. }
  228. }