bianjunhui пре 1 недеља
родитељ
комит
b6c45b2f4c

+ 62 - 0
packages/Longyi/RewardPoints/src/Helpers/ApiResponse.php

@@ -0,0 +1,62 @@
+<?php
+
+namespace Longyi\RewardPoints\Helpers;
+
+class ApiResponse
+{
+    /**
+     * 成功响应
+     */
+    public static function success($data = [], string $message = 'Success', int $code = 200)
+    {
+        return response()->json([
+            'success' => true,
+            'message' => $message,
+            'data' => $data
+        ], $code);
+    }
+
+    /**
+     * 错误响应
+     */
+    public static function error(string $message, $data = [], int $code = 400)
+    {
+        return response()->json([
+            'success' => false,
+            'message' => $message,
+            'data' => $data
+        ], $code);
+    }
+
+    /**
+     * 未授权响应
+     */
+    public static function unauthorized(string $message = 'Please login first')
+    {
+        return self::error($message, [], 401);
+    }
+
+    /**
+     * 禁止访问响应
+     */
+    public static function forbidden(string $message = 'Access denied')
+    {
+        return self::error($message, [], 403);
+    }
+
+    /**
+     * 未找到响应
+     */
+    public static function notFound(string $message = 'Resource not found')
+    {
+        return self::error($message, [], 404);
+    }
+
+    /**
+     * 验证错误响应
+     */
+    public static function validationError(string $message, $errors = [])
+    {
+        return self::error($message, $errors, 422);
+    }
+}

+ 190 - 46
packages/Longyi/RewardPoints/src/Http/Controllers/RewardPointsController.php

@@ -2,22 +2,27 @@
 
 namespace Longyi\RewardPoints\Http\Controllers;
 
+use Longyi\RewardPoints\Models\RewardActiveRule;
 use Longyi\RewardPoints\Repositories\RewardPointRepository;
+use Longyi\RewardPoints\Repositories\RewardPointSettingRepository;
 use Longyi\RewardPoints\Models\RewardPointCustomerSign;
-use Longyi\RewardPoints\Models\RewardActiveRule;
+use Longyi\RewardPoints\Helpers\ApiResponse;
 use Carbon\Carbon;
 use Illuminate\Http\Request;
 use Illuminate\Routing\Controller;
-use Webkul\User\Repositories\RoleRepository;
-use Illuminate\Support\Facades\DB;
+
 class RewardPointsController extends Controller
 {
     protected $rewardPointRepository;
+    protected $settingRepository;
     protected $_config;
 
-    public function __construct(RewardPointRepository $rewardPointRepository)
-    {
+    public function __construct(
+        RewardPointRepository $rewardPointRepository,
+        RewardPointSettingRepository $settingRepository
+    ) {
         $this->rewardPointRepository = $rewardPointRepository;
+        $this->settingRepository = $settingRepository;
         $this->_config = request('_config');
     }
 
@@ -37,11 +42,16 @@ class RewardPointsController extends Controller
 
     public function signIn()
     {
-
         $customer = auth()->guard('customer')->user();
 
         if (!$customer) {
-            return response()->json(['error' => 'Please login first'], 401);
+            return ApiResponse::unauthorized();
+        }
+
+        // Check if sign in feature is enabled
+        $signinEnabled = $this->settingRepository->getConfigValue('signin_enabled', true);
+        if (!$signinEnabled) {
+            return ApiResponse::forbidden('Sign in feature is disabled');
         }
 
         $today = Carbon::now()->format('Y-m-d');
@@ -51,7 +61,7 @@ class RewardPointsController extends Controller
             ->first();
 
         if ($existingSign) {
-            return response()->json(['error' => 'Already signed in today'], 400);
+            return ApiResponse::error('Already signed in today');
         }
 
         $lastSign = RewardPointCustomerSign::where('customer_id', $customer->id)
@@ -70,8 +80,10 @@ class RewardPointsController extends Controller
             }
         }
 
+        // Get sign in points from ly_mw_reward_points_settings table
         $points = $this->getSignInPointsByDay($countDate);
 
+        // Create sign in record (Laravel auto-maintains created_at and updated_at)
         $sign = RewardPointCustomerSign::create([
             'customer_id' => $customer->id,
             'sign_date' => $today,
@@ -80,52 +92,54 @@ class RewardPointsController extends Controller
             'code' => uniqid('SIGN_')
         ]);
 
+        // Add points to customer account
         $this->rewardPointRepository->addPoints(
             $customer->id,
-            RewardActiveRule::TYPE_SIGN_IN,
+       RewardActiveRule::TYPE_SIGN_IN,
             $points,
             null,
             "Daily sign-in reward (Day {$countDate})"
         );
 
-        return response()->json([
-            'success' => true,
+        $totalPoints = $this->rewardPointRepository->getCustomerPoints($customer->id);
+
+        return ApiResponse::success([
             'points' => $points,
             'streak' => $countDate,
-            'total_points' => $this->rewardPointRepository->getCustomerPoints($customer->id)
-        ]);
+            'total_points' => $totalPoints
+        ], "Sign in successful! Earned {$points} points");
     }
 
     /**
-     * 根据签到天数获取对应的积分
+     * Get sign in points by day from ly_mw_reward_points_settings table
      */
     protected function getSignInPointsByDay($day)
     {
-        $settingRepository = app(\Longyi\RewardPoints\Repositories\RewardPointSettingRepository::class);
-
+        // Map sign in days to configuration codes
         $dayPointsMap = [
-            1 => $settingRepository->getConfigValue('signin_day1_points', 10),
-            2 => $settingRepository->getConfigValue('signin_day2_points', 10),
-            3 => $settingRepository->getConfigValue('signin_day3_points', 15),
-            4 => $settingRepository->getConfigValue('signin_day4_points', 25),
-            5 => $settingRepository->getConfigValue('signin_day5_points', 50),
-            6 => $settingRepository->getConfigValue('signin_day6_points', 70),
-            7 => $settingRepository->getConfigValue('signin_day7_points', 70),
+            1 => 'signin_day1_points',
+            2 => 'signin_day2_points',
+            3 => 'signin_day3_points',
+            4 => 'signin_day4_points',
+            5 => 'signin_day5_points',
+            6 => 'signin_day6_points',
+            7 => 'signin_day7_points',
         ];
 
-        if ($day <= 7) {
-            return (int) $dayPointsMap[$day];
+        // If <= 7 days, use corresponding configuration
+        if ($day <= 7 && isset($dayPointsMap[$day])) {
+            return (int) $this->settingRepository->getConfigValue($dayPointsMap[$day], 10);
         }
 
-        return (int) $settingRepository->getConfigValue('signin_day8_plus_points', 70);
+        // 8 days and beyond, use signin_day8_plus_points configuration
+        return (int) $this->settingRepository->getConfigValue('signin_day8_plus_points', 70);
     }
 
     public function getSignStatus()
     {
         $customer = auth()->guard('customer')->user();
-
         if (!$customer) {
-            return response()->json(['error' => 'Please login first'], 401);
+            return ApiResponse::unauthorized();
         }
 
         $today = Carbon::now()->format('Y-m-d');
@@ -137,13 +151,118 @@ class RewardPointsController extends Controller
             ->orderBy('sign_date', 'desc')
             ->first();
 
-        return response()->json([
+        return ApiResponse::success([
             'signed_today' => $signedToday,
             'current_streak' => $lastSign ? $lastSign->count_date : 0,
             'total_points' => $this->rewardPointRepository->getCustomerPoints($customer->id)
         ]);
     }
 
+    /**
+     * Get customer points history/records
+     *
+     * @param Request $request
+     * @return \Illuminate\Http\JsonResponse
+     */
+    public function getPointsHistory(Request $request)
+    {
+        $customer = auth()->guard('customer')->user();
+
+        if (!$customer) {
+            return ApiResponse::unauthorized();
+        }
+
+        // Get pagination parameters
+        $page = $request->input('page', 1);
+        $limit = $request->input('per_page', 20);
+
+        // Validate limit
+        $limit = min(max($limit, 1), 100); // Limit between 1 and 100
+
+        // Get paginated history
+        $history = $this->rewardPointRepository->getHistory($customer->id, $limit);
+
+        // Transform history data
+        $transformedHistory = collect($history->items())->map(function ($item) {
+            return [
+                'id' => $item->history_id,
+                'type' => $item->type_of_transaction,
+                'type_text' => $this->getTransactionTypeText($item->type_of_transaction),
+                'amount' => $item->amount,
+                'balance' => $item->balance,
+                'detail' => $item->transaction_detail,
+                'order_id' => $item->history_order_id > 0 ? $item->history_order_id : null,
+                'expired_day' => $item->expired_day,
+                'expired_time' => $item->expired_time ? Carbon::parse($item->expired_time)->format('Y-m-d H:i:s') : null,
+                'remaining_points' => $item->point_remaining,
+                'status' => $item->status,
+                'status_text' => $this->getStatusText($item->status),
+                'created_at' => Carbon::parse($item->transaction_time)->format('Y-m-d H:i:s'),
+            ];
+        });
+
+        return ApiResponse::success([
+            'current_points' => $this->rewardPointRepository->getCustomerPoints($customer->id),
+            'history' => $transformedHistory,
+            'pagination' => [
+                'current_page' => $history->currentPage(),
+                'per_page' => $history->perPage(),
+                'total' => $history->total(),
+                'last_page' => $history->lastPage(),
+                'has_more' => $history->hasMorePages()
+            ]
+        ]);
+    }
+
+    /**
+     * Get customer points summary
+     *
+     * @return \Illuminate\Http\JsonResponse
+     */
+    public function getPointsSummary()
+    {
+        $customer = auth()->guard('customer')->user();
+
+        if (!$customer) {
+            return ApiResponse::unauthorized();
+        }
+
+        $totalPoints = $this->rewardPointRepository->getCustomerPoints($customer->id);
+
+        // Get today's sign in status
+        $today = Carbon::now()->format('Y-m-d');
+        $signedToday = RewardPointCustomerSign::where('customer_id', $customer->id)
+            ->where('sign_date', $today)
+            ->exists();
+
+        // Get current streak
+        $lastSign = RewardPointCustomerSign::where('customer_id', $customer->id)
+            ->orderBy('sign_date', 'desc')
+            ->first();
+        $currentStreak = $lastSign ? $lastSign->count_date : 0;
+
+        // Get total earned points (all time)
+        $totalEarned = $this->model
+            ->where('customer_id', $customer->id)
+            ->where('amount', '>', 0)
+            ->sum('amount');
+
+        // Get total used points (all time)
+        $totalUsed = $this->model
+                ->where('customer_id', $customer->id)
+                ->where('amount', '<', 0)
+                ->sum('amount') * -1;
+
+        return ApiResponse::success([
+            'current_points' => $totalPoints,
+            'total_earned' => $totalEarned,
+            'total_used' => $totalUsed,
+            'signed_today' => $signedToday,
+            'current_streak' => $currentStreak,
+            'points_value' => $totalPoints * (float) $this->settingRepository->getConfigValue('point_value', 0.01)
+        ]);
+    }
+
     /**
      * Apply reward points to cart
      */
@@ -155,10 +274,7 @@ class RewardPointsController extends Controller
         $validation = $cartRewardPoints->validatePoints($points);
 
         if ($validation !== true) {
-            return response()->json([
-                'success' => false,
-                'message' => $validation
-            ], 400);
+            return ApiResponse::error($validation);
         }
 
         $result = $cartRewardPoints->applyPoints($points);
@@ -166,17 +282,12 @@ class RewardPointsController extends Controller
         if ($result) {
             $discountDetails = $cartRewardPoints->getDiscountDetails();
 
-            return response()->json([
-                'success' => true,
-                'message' => 'Reward points applied successfully',
+            return ApiResponse::success([
                 'discount' => $discountDetails
-            ]);
+            ], 'Reward points applied successfully');
         }
 
-        return response()->json([
-            'success' => false,
-            'message' => 'Failed to apply reward points'
-        ], 400);
+        return ApiResponse::error('Failed to apply reward points');
     }
 
     /**
@@ -187,10 +298,7 @@ class RewardPointsController extends Controller
         $cartRewardPoints = app('cartrewardpoints');
         $cartRewardPoints->removePoints();
 
-        return response()->json([
-            'success' => true,
-            'message' => 'Reward points removed successfully'
-        ]);
+        return ApiResponse::success([], 'Reward points removed successfully');
     }
 
     /**
@@ -200,7 +308,7 @@ class RewardPointsController extends Controller
     {
         $cartRewardPoints = app('cartrewardpoints');
 
-        return response()->json([
+        return ApiResponse::success([
             'available_points' => $cartRewardPoints->getAvailablePoints(),
             'points_used' => $cartRewardPoints->getPointsUsed(),
             'discount_amount' => $cartRewardPoints->getDiscountAmount(),
@@ -208,4 +316,40 @@ class RewardPointsController extends Controller
             'max_points_allowed' => $cartRewardPoints->getMaxPointsByCartTotal()
         ]);
     }
+
+    /**
+     * Get transaction type text
+     */
+    protected function getTransactionTypeText($type)
+    {
+        $types = [
+            1 => 'Daily Sign In',
+            2 => 'Registration',
+            3 => 'Order Purchase',
+            4 => 'Product Review',
+            5 => 'Referral',
+            6 => 'Birthday',
+            7 => 'Share',
+            8 => 'Subscription',
+            9 => 'Login',
+        ];
+
+        return $types[$type] ?? 'Unknown';
+    }
+
+    /**
+     * Get status text
+     */
+    protected function getStatusText($status)
+    {
+        $statuses = [
+            0 => 'Completed',
+            1 => 'Pending',
+            2 => 'Expired',
+            3 => 'Cancelled'
+        ];
+
+        return $statuses[$status] ?? 'Unknown';
+    }
 }
+

+ 1 - 1
packages/Longyi/RewardPoints/src/Models/RewardActiveRule.php

@@ -15,7 +15,7 @@ class RewardActiveRule extends Model
     const TYPE_BIRTHDAY = 6;       // 生日
     const TYPE_SHARE  = 7;         // 分享
     const TYPE_SUBSCRIBE  = 8;         // 关注
-    const TYPE_LOGIN = 1;        // 登录
+    const TYPE_LOGIN = 9;        // 登录
     protected $table = 'mw_reward_active_rules';
 
     protected $primaryKey = 'rule_id';

+ 30 - 0
packages/Longyi/RewardPoints/src/Routes/routes.php

@@ -22,6 +22,16 @@ Route::group(['middleware' => ['web', 'customer'], 'prefix' => 'customer'], func
         'uses' => 'Longyi\RewardPoints\Http\Controllers\RewardPointsController@getSignStatus'
     ]);
 
+    Route::get('reward-points/history', [
+        'as' => 'customer.reward-points.history',
+        'uses' => 'Longyi\RewardPoints\Http\Controllers\RewardPointsController@getPointsHistory'
+    ]);
+
+    Route::get('reward-points/summary', [
+        'as' => 'customer.reward-points.summary',
+        'uses' => 'Longyi\RewardPoints\Http\Controllers\RewardPointsController@getPointsSummary'
+    ]);
+
     Route::post('apply-reward-points', [
         'as' => 'checkout.apply-reward-points',
         'uses' => 'Longyi\RewardPoints\Http\Controllers\RewardPointsController@applyPoints'
@@ -45,6 +55,21 @@ Route::group(['middleware' => ['api', ApiCustomerAuthenticate::class], 'prefix'
         'uses' => 'Longyi\RewardPoints\Http\Controllers\RewardPointsController@signIn'
     ]);
 
+    Route::get('reward-points/history', [
+        'as' => 'api.customer.reward-points.history',
+        'uses' => 'Longyi\RewardPoints\Http\Controllers\RewardPointsController@getPointsHistory'
+    ]);
+
+    Route::get('reward-points/summary', [
+        'as' => 'api.customer.reward-points.summary',
+        'uses' => 'Longyi\RewardPoints\Http\Controllers\RewardPointsController@getPointsSummary'
+    ]);
+
+    Route::get('reward-points/sign-status', [
+        'as' => 'api.customer.reward-points.sign-status',
+        'uses' => 'Longyi\RewardPoints\Http\Controllers\RewardPointsController@getSignStatus'
+    ]);
+
     Route::post('apply-reward-points', [
         'as' => 'api.checkout.apply-reward-points',
         'uses' => 'Longyi\RewardPoints\Http\Controllers\RewardPointsController@applyPoints'
@@ -54,6 +79,11 @@ Route::group(['middleware' => ['api', ApiCustomerAuthenticate::class], 'prefix'
         'as' => 'api.checkout.remove-reward-points',
         'uses' => 'Longyi\RewardPoints\Http\Controllers\RewardPointsController@removePoints'
     ]);
+
+    Route::get('reward-points-info', [
+        'as' => 'api.checkout.reward-points-info',
+        'uses' => 'Longyi\RewardPoints\Http\Controllers\RewardPointsController@getPointsInfo'
+    ]);
 });
 
 // 后台路由