RewardPointsController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. <?php
  2. namespace Longyi\RewardPoints\Http\Controllers;
  3. use Illuminate\Support\Facades\Log;
  4. use Longyi\RewardPoints\Models\RewardActiveRule;
  5. use Longyi\RewardPoints\Repositories\RewardPointRepository;
  6. use Longyi\RewardPoints\Repositories\RewardPointSettingRepository;
  7. use Longyi\RewardPoints\Models\RewardPointCustomerSign;
  8. use Longyi\RewardPoints\Helpers\ApiResponse;
  9. use Carbon\Carbon;
  10. use Illuminate\Http\Request;
  11. use Illuminate\Routing\Controller;
  12. use Longyi\RewardPoints\Models\RewardPointHistory;
  13. class RewardPointsController extends Controller
  14. {
  15. protected $rewardPointRepository;
  16. protected $settingRepository;
  17. protected $_config;
  18. public function __construct(
  19. RewardPointRepository $rewardPointRepository,
  20. RewardPointSettingRepository $settingRepository
  21. ) {
  22. $this->rewardPointRepository = $rewardPointRepository;
  23. $this->settingRepository = $settingRepository;
  24. $this->_config = request('_config');
  25. }
  26. public function index()
  27. {
  28. $customer = auth()->guard('customer')->user();
  29. if (!$customer) {
  30. return redirect()->route('customer.session.index');
  31. }
  32. $points = $this->rewardPointRepository->getCustomerPoints($customer->id);
  33. $history = $this->rewardPointRepository->getHistory($customer->id);
  34. return view($this->_config['view'], compact('points', 'history'));
  35. }
  36. public function signIn()
  37. {
  38. $customer = auth()->guard('customer')->user();
  39. if (!$customer) {
  40. return ApiResponse::unauthorized();
  41. }
  42. // Check if sign in feature is enabled
  43. $signinEnabled = $this->settingRepository->getConfigValue('signin_enabled', true);
  44. if (!$signinEnabled) {
  45. return ApiResponse::forbidden('Sign in feature is disabled');
  46. }
  47. $today = Carbon::now()->format('Y-m-d');
  48. $existingSign = RewardPointCustomerSign::where('customer_id', $customer->id)
  49. ->where('sign_date', $today)
  50. ->first();
  51. if ($existingSign) {
  52. return ApiResponse::error('Already signed in today');
  53. }
  54. $lastSign = RewardPointCustomerSign::where('customer_id', $customer->id)
  55. ->orderBy('sign_date', 'desc')
  56. ->first();
  57. $countDate = 1;
  58. if ($lastSign) {
  59. $lastSignDate = Carbon::parse($lastSign->sign_date);
  60. $yesterday = Carbon::yesterday();
  61. if ($lastSignDate->toDateString() === $yesterday->toDateString()) {
  62. $countDate = $lastSign->count_date + 1;
  63. } elseif ($lastSignDate->toDateString() !== $today) {
  64. $countDate = 1;
  65. }
  66. }
  67. // Get sign in points from ly_mw_reward_points_settings table
  68. $points = $this->getSignInPointsByDay($countDate);
  69. // Create sign in record (Laravel auto-maintains created_at and updated_at)
  70. $sign = RewardPointCustomerSign::create([
  71. 'customer_id' => $customer->id,
  72. 'sign_date' => $today,
  73. 'count_date' => $countDate,
  74. 'point' => $points,
  75. 'code' => uniqid('SIGN_')
  76. ]);
  77. // Add points to customer account
  78. $this->rewardPointRepository->addPoints(
  79. $customer->id,
  80. RewardActiveRule::TYPE_SIGN_IN,
  81. $points,
  82. null,
  83. "Daily sign-in reward (Day {$countDate})"
  84. );
  85. $totalPoints = $this->rewardPointRepository->getCustomerPoints($customer->id);
  86. return ApiResponse::success([
  87. 'points' => $points,
  88. 'streak' => $countDate,
  89. 'total_points' => $totalPoints
  90. ], "Sign in successful! Earned {$points} points");
  91. }
  92. /**
  93. * Get sign in points by day from ly_mw_reward_points_settings table
  94. */
  95. protected function getSignInPointsByDay($day)
  96. {
  97. // Map sign in days to configuration codes
  98. $dayPointsMap = [
  99. 1 => 'signin_day1_points',
  100. 2 => 'signin_day2_points',
  101. 3 => 'signin_day3_points',
  102. 4 => 'signin_day4_points',
  103. 5 => 'signin_day5_points',
  104. 6 => 'signin_day6_points',
  105. 7 => 'signin_day7_points',
  106. ];
  107. // If <= 7 days, use corresponding configuration
  108. if ($day <= 7 && isset($dayPointsMap[$day])) {
  109. return (int) $this->settingRepository->getConfigValue($dayPointsMap[$day], 10);
  110. }
  111. // 8 days and beyond, use signin_day8_plus_points configuration
  112. return (int) $this->settingRepository->getConfigValue('signin_day8_plus_points', 70);
  113. }
  114. public function getSignStatus()
  115. {
  116. $customer = auth()->guard('customer')->user();
  117. if (!$customer) {
  118. return ApiResponse::unauthorized();
  119. }
  120. Log::info('Customer login event triggered');
  121. $today = Carbon::now()->format('Y-m-d');
  122. $signedToday = RewardPointCustomerSign::where('customer_id', $customer->id)
  123. ->where('sign_date', $today)
  124. ->exists();
  125. $lastSign = RewardPointCustomerSign::where('customer_id', $customer->id)
  126. ->orderBy('sign_date', 'desc')
  127. ->first();
  128. /*$currentGroup = 'sign_in';
  129. $settings = $this->settingRepository->getSettingsByGroup($currentGroup);*/
  130. return ApiResponse::success([
  131. 'signed_today' => $signedToday,
  132. 'current_streak' => $lastSign ? $lastSign->count_date : 0,
  133. 'total_points' => $this->rewardPointRepository->getCustomerPoints($customer->id)
  134. ]);
  135. }
  136. /**
  137. * Get customer points history/records
  138. *
  139. * @param Request $request
  140. * @return \Illuminate\Http\JsonResponse
  141. */
  142. public function getPointsHistory(Request $request)
  143. {
  144. $customer = auth()->guard('customer')->user();
  145. if (!$customer) {
  146. return ApiResponse::unauthorized();
  147. }
  148. // Get pagination parameters
  149. $page = $request->input('page', 1);
  150. $limit = $request->input('per_page', 20);
  151. // Validate limit
  152. $limit = min(max($limit, 1), 100); // Limit between 1 and 100
  153. // Get paginated history
  154. $history = $this->rewardPointRepository->getHistory($customer->id, $limit,$page);
  155. // Transform history data
  156. $transformedHistory = collect($history->items())->map(function ($item) {
  157. return [
  158. 'id' => $item->history_id,
  159. 'type' => $item->type_of_transaction,
  160. 'type_text' => $this->getTransactionTypeText($item->type_of_transaction),
  161. 'amount' => $item->amount,
  162. 'balance' => $item->balance,
  163. 'detail' => $item->transaction_detail,
  164. 'order_id' => $item->history_order_id > 0 ? $item->history_order_id : null,
  165. 'expired_day' => $item->expired_day,
  166. 'expired_time' => $item->expired_time ? Carbon::parse($item->expired_time)->format('Y-m-d H:i:s') : null,
  167. 'remaining_points' => $item->point_remaining,
  168. 'status' => $item->status,
  169. 'status_text' => $this->getStatusText($item->status),
  170. 'created_at' => Carbon::parse($item->transaction_time)->format('Y-m-d H:i:s'),
  171. ];
  172. });
  173. return ApiResponse::success([
  174. 'current_points' => $this->rewardPointRepository->getCustomerPoints($customer->id),
  175. 'history' => $transformedHistory,
  176. 'pagination' => [
  177. 'current_page' => $history->currentPage(),
  178. 'per_page' => $history->perPage(),
  179. 'total' => $history->total(),
  180. 'last_page' => $history->lastPage(),
  181. 'has_more' => $history->hasMorePages()
  182. ]
  183. ]);
  184. }
  185. /**
  186. * Get customer points summary
  187. *
  188. * @return \Illuminate\Http\JsonResponse
  189. */
  190. public function getPointsSummary()
  191. {
  192. $customer = auth()->guard('customer')->user();
  193. if (!$customer) {
  194. return ApiResponse::unauthorized();
  195. }
  196. $totalPoints = $this->rewardPointRepository->getCustomerPoints($customer->id);
  197. // Get today's sign in status
  198. $today = Carbon::now()->format('Y-m-d');
  199. $signedToday = RewardPointCustomerSign::where('customer_id', $customer->id)
  200. ->where('sign_date', $today)
  201. ->exists();
  202. // Get current streak
  203. $lastSign = RewardPointCustomerSign::where('customer_id', $customer->id)
  204. ->orderBy('sign_date', 'desc')
  205. ->first();
  206. $currentStreak = $lastSign ? $lastSign->count_date : 0;
  207. // Get total earned points (all time)
  208. $totalEarned = RewardPointHistory::where('customer_id', $customer->id)
  209. ->where('amount', '>', 0)
  210. ->sum('amount');
  211. // Get total used points (all time)
  212. $totalUsed = RewardPointHistory::where('customer_id', $customer->id)
  213. ->where('amount', '<', 0)
  214. ->sum('amount') * -1;
  215. return ApiResponse::success([
  216. 'current_points' => $totalPoints,
  217. 'total_earned' => $totalEarned,
  218. 'total_used' => $totalUsed,
  219. 'signed_today' => $signedToday,
  220. 'current_streak' => $currentStreak,
  221. 'points_value' => $totalPoints * (float) $this->settingRepository->getConfigValue('point_value', 0.01)
  222. ]);
  223. }
  224. /**
  225. * Apply reward points to cart
  226. */
  227. public function applyPoints(Request $request)
  228. {
  229. $points = $request->input('points', 0);
  230. $cartRewardPoints = app('cartrewardpoints');
  231. $validation = $cartRewardPoints->validatePoints($points);
  232. if ($validation !== true) {
  233. return ApiResponse::error($validation);
  234. }
  235. $result = $cartRewardPoints->applyPoints($points);
  236. if ($result) {
  237. $discountDetails = $cartRewardPoints->getDiscountDetails();
  238. return ApiResponse::success([
  239. 'discount' => $discountDetails
  240. ], 'Reward points applied successfully');
  241. }
  242. return ApiResponse::error('Failed to apply reward points');
  243. }
  244. /**
  245. * Remove reward points from cart
  246. */
  247. public function removePoints()
  248. {
  249. $cartRewardPoints = app('cartrewardpoints');
  250. $cartRewardPoints->removePoints();
  251. return ApiResponse::success([], 'Reward points removed successfully');
  252. }
  253. /**
  254. * Get points information for cart
  255. */
  256. public function getPointsInfo()
  257. {
  258. $cartRewardPoints = app('cartrewardpoints');
  259. return ApiResponse::success([
  260. 'available_points' => $cartRewardPoints->getAvailablePoints(),
  261. 'points_used' => $cartRewardPoints->getPointsUsed(),
  262. 'discount_amount' => $cartRewardPoints->getDiscountAmount(),
  263. 'points_value' => $cartRewardPoints->getPointsValue(1),
  264. 'max_points_allowed' => $cartRewardPoints->getMaxPointsByCartTotal()
  265. ]);
  266. }
  267. /**
  268. * Get transaction type text
  269. */
  270. protected function getTransactionTypeText($type)
  271. {
  272. $types = [
  273. 1 => 'Daily Sign In',
  274. 2 => 'Registration',
  275. 3 => 'Order Purchase',
  276. 4 => 'Product Review',
  277. 5 => 'Referral',
  278. 6 => 'Birthday',
  279. 7 => 'Share',
  280. 8 => 'Subscription',
  281. 9 => 'Login',
  282. ];
  283. return $types[$type] ?? 'Unknown';
  284. }
  285. /**
  286. * Get status text
  287. */
  288. protected function getStatusText($status)
  289. {
  290. $statuses = [
  291. 1 => 'Completed',
  292. 0 => 'Pending',
  293. 3 => 'Expired',
  294. 2 => 'Cancelled'
  295. ];
  296. return $statuses[$status] ?? 'Unknown';
  297. }
  298. }