소스 검색

feat:技师端-获取技师钱包信息

刘学玺 4 달 전
부모
커밋
03bc58d219
4개의 변경된 파일259개의 추가작업 그리고 11개의 파일을 삭제
  1. 91 0
      app/Http/Controllers/Coach/WalletController.php
  2. 0 10
      app/Models/CoachUser.php
  3. 160 0
      app/Services/Coach/WalletService.php
  4. 8 1
      routes/api.php

+ 91 - 0
app/Http/Controllers/Coach/WalletController.php

@@ -0,0 +1,91 @@
+<?php
+
+namespace App\Http\Controllers\Coach;
+
+use App\Http\Controllers\Controller;
+use App\Services\Coach\WalletService;
+use App\Traits\ResponseTrait;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Auth;
+
+/**
+ * @group 技师端
+ *
+ * 钱包相关的API接口
+ */
+class WalletController extends Controller
+{
+    use ResponseTrait;
+
+    protected WalletService $service;
+
+    public function __construct(WalletService $service)
+    {
+        $this->service = $service;
+    }
+
+    /**
+     * [钱包]获取钱包信息
+     *
+     * @description 获取技师钱包余额和收入统计信息
+     *
+     * @authenticated
+     *
+     * @response {
+     *   "data": {
+     *     "balance": "1000.00",
+     *     "frozen_amount": "0.00",
+     *     "total_income": "5000.00",
+     *     "total_withdraw": "4000.00",
+     *     "today_income": "100.00",
+     *     "month_income": "2000.00",
+     *     "last_month_income": "3000.00"
+     *   }
+     * }
+     */
+    public function getWallet()
+    {
+        return $this->success($this->service->getWallet(Auth::user()->id));
+    }
+
+    /**
+     * [钱包]获取钱包流水记录
+     *
+     * @description 获取技师钱包的收支明细记录
+     *
+     * @authenticated
+     *
+     * @queryParam type integer 记录类型(1:收入 2:支出) Example: 1
+     * @queryParam start_date date 开始日期 Example: 2024-01-01
+     * @queryParam end_date date 结束日期 Example: 2024-03-21
+     * @queryParam page integer 页码 Example: 1
+     * @queryParam per_page integer 每页数量 Example: 10
+     *
+     * @response {
+     *   "data": {
+     *     "items": [
+     *       {
+     *         "id": 1,
+     *         "amount": "100.00",
+     *         "type": 1,
+     *         "remark": "订单收入",
+     *         "created_at": "2024-03-21 10:00:00"
+     *       }
+     *     ],
+     *     "total": 100
+     *   }
+     * }
+     */
+    public function getWalletRecords(Request $request)
+    {
+        $params = $request->validate([
+            'type' => 'nullable|integer|in:1,2',
+            'start_date' => 'nullable|date',
+            'end_date' => 'nullable|date|after_or_equal:start_date',
+            'page' => 'nullable|integer|min:1',
+            'per_page' => 'nullable|integer|min:1|max:50',
+        ]);
+
+        return $this->success($this->service->getWalletRecords(Auth::user()->id, $params));
+    }
+}

+ 0 - 10
app/Models/CoachUser.php

@@ -96,16 +96,6 @@ class CoachUser extends Model
         return $this->hasMany('App\Models\OrderComment', 'coach_id', 'id');
     }
 
-    /**
-     * @Author FelixYin
-     *
-     * @description 技师关联钱包
-     */
-    public function wallet()
-    {
-        return $this->MORPH_ONE('App\Models\Wallet', 'undefined');
-    }
-
     /**
      * @Author FelixYin
      *

+ 160 - 0
app/Services/Coach/WalletService.php

@@ -0,0 +1,160 @@
+<?php
+
+namespace App\Services\Coach;
+
+use App\Models\MemberUser;
+use App\Models\WalletTransRecord;
+use Illuminate\Support\Facades\Log;
+
+class WalletService
+{
+    /**
+     * 获取技师钱包信息
+     *
+     * @param  int  $userId  技师用户ID
+     */
+    public function getWallet(int $userId): array
+    {
+        try {
+            // 加载用户和技师信息
+            $user = MemberUser::with(['coach', 'coach.wallet'])->findOrFail($userId);
+            abort_if(! $user->coach, 404, '技师信息不存在');
+
+            // 获取技师钱包
+            $wallet = $user->coach->wallet;
+
+            // 获取钱包流水统计
+            $statistics = $this->getWalletStatistics($wallet->id);
+
+            return [
+                'available_balance' => number_format($wallet->available_balance, 2, '.', ''), // 可用余额
+                'frozen_amount' => number_format($wallet->frozen_amount, 2, '.', ''), // 冻结金额
+                'total_income' => number_format($statistics['total_income'], 2, '.', ''), // 累计收入
+                'total_withdraw' => number_format($statistics['total_withdraw'], 2, '.', ''), // 累计支出
+                'today_income' => number_format($statistics['today_income'], 2, '.', ''), // 今日收入
+                'month_income' => number_format($statistics['month_income'], 2, '.', ''), // 本月收入
+                'last_month_income' => number_format($statistics['last_month_income'], 2, '.', ''), // 上月收入
+            ];
+
+        } catch (\Exception $e) {
+            Log::error('获取技师钱包信息失败', [
+                'user_id' => $userId,
+                'error' => $e->getMessage(),
+                'file' => $e->getFile(),
+                'line' => $e->getLine(),
+            ]);
+            throw $e;
+        }
+    }
+
+    /**
+     * 获取钱包流水记录
+     *
+     * @param  int  $userId  技师用户ID
+     * @param  array  $params  查询参数
+     */
+    public function getWalletRecords(int $userId, array $params): array
+    {
+        try {
+            // 加载用户和钱包信息
+            $user = MemberUser::with(['wallet'])->findOrFail($userId);
+            abort_if(! $user->wallet, 404, '钱包信息不存在');
+
+            // 构建查询
+            $query = WalletTransRecord::where('wallet_id', $user->wallet->id)
+                ->when(isset($params['type']), function ($query) use ($params) {
+                    return $query->where('type', $params['type']);
+                })
+                ->when(isset($params['start_date']), function ($query) use ($params) {
+                    return $query->where('created_at', '>=', $params['start_date']);
+                })
+                ->when(isset($params['end_date']), function ($query) use ($params) {
+                    return $query->where('created_at', '<=', $params['end_date']);
+                })
+                ->orderBy('created_at', 'desc');
+
+            // 分页获取数据
+            $records = $query->paginate(
+                $params['per_page'] ?? 10,
+                ['*'],
+                'page',
+                $params['page'] ?? 1
+            );
+
+            return [
+                'items' => $records->items(),
+                'total' => $records->total(),
+            ];
+
+        } catch (\Exception $e) {
+            Log::error('获取钱包流水记录失败', [
+                'user_id' => $userId,
+                'params' => $params,
+                'error' => $e->getMessage(),
+                'file' => $e->getFile(),
+                'line' => $e->getLine(),
+            ]);
+            throw $e;
+        }
+    }
+
+    /**
+     * 获取钱包流水统计
+     *
+     * @param  int  $walletId  钱包ID
+     */
+    private function getWalletStatistics(int $walletId): array
+    {
+        try {
+            // 计算总收入和总支出
+            $totals = WalletTransRecord::where('wallet_id', $walletId)
+                ->selectRaw('
+                    SUM(CASE WHEN amount > 0 THEN amount ELSE 0 END) as total_income,
+                    ABS(SUM(CASE WHEN amount < 0 THEN amount ELSE 0 END)) as total_withdraw
+                ')
+                ->first();
+
+            // 计算今日收入
+            $todayIncome = WalletTransRecord::where('wallet_id', $walletId)
+                ->where('amount', '>', 0)
+                ->whereDate('created_at', today())
+                ->sum('amount');
+
+            // 计算本月收入
+            $monthIncome = WalletTransRecord::where('wallet_id', $walletId)
+                ->where('amount', '>', 0)
+                ->whereYear('created_at', now()->year)
+                ->whereMonth('created_at', now()->month)
+                ->sum('amount');
+
+            // 计算上月收入
+            $lastMonthIncome = WalletTransRecord::where('wallet_id', $walletId)
+                ->where('amount', '>', 0)
+                ->whereYear('created_at', now()->subMonth()->year)
+                ->whereMonth('created_at', now()->subMonth()->month)
+                ->sum('amount');
+
+            return [
+                'total_income' => $totals->total_income ?? 0,
+                'total_withdraw' => $totals->total_withdraw ?? 0,
+                'today_income' => $todayIncome,
+                'month_income' => $monthIncome,
+                'last_month_income' => $lastMonthIncome,
+            ];
+
+        } catch (\Exception $e) {
+            Log::error('获取钱包统计信息失败', [
+                'wallet_id' => $walletId,
+                'error' => $e->getMessage(),
+            ]);
+
+            return [
+                'total_income' => 0,
+                'total_withdraw' => 0,
+                'today_income' => 0,
+                'month_income' => 0,
+                'last_month_income' => 0,
+            ];
+        }
+    }
+}

+ 8 - 1
routes/api.php

@@ -11,6 +11,7 @@ use App\Http\Controllers\Client\UserController;
 use App\Http\Controllers\Client\WalletController;
 use App\Http\Controllers\Coach\OrderController as CoachOrderController;
 use App\Http\Controllers\Coach\ProjectController as CoachProjectController;
+use App\Http\Controllers\Coach\WalletController as CoachWalletController;
 use App\Http\Controllers\EnumController;
 use App\Http\Controllers\ScribeController;
 use Illuminate\Support\Facades\Route;
@@ -24,7 +25,7 @@ Route::prefix('client')->group(function () {
 
     // 无需认证的公开路由
     Route::prefix('account')->group(function () {
-        // 发验证码
+        // 发��验证码
         Route::post('send-code', [AccountController::class, 'sendVerifyCode']);
         // 手机号登录
         Route::post('login', [AccountController::class, 'login']);
@@ -159,4 +160,10 @@ Route::middleware(['auth:sanctum', 'verified'])->prefix('coach')->group(function
         Route::post('/open', [CoachProjectController::class, 'openProject']);
         Route::post('/set', [CoachProjectController::class, 'setProject']);
     });
+
+    // 钱包相关路由
+    Route::prefix('wallet')->group(function () {
+        Route::get('/', [CoachWalletController::class, 'getWallet']);
+        Route::get('/records', [CoachWalletController::class, 'getWalletRecords']);
+    });
 });