소스 검색

fixed:同步代码编写规范

Yin Bin 4 달 전
부모
커밋
4e331392b9
2개의 변경된 파일84개의 추가작업 그리고 91개의 파일을 삭제
  1. 75 83
      app/Services/Client/OrderService.php
  2. 9 8
      app/Services/Client/ProjectService.php

+ 75 - 83
app/Services/Client/OrderService.php

@@ -36,6 +36,13 @@ class OrderService
 
     /**
      * 订单初始化
+     *
+     * 初始化订单信息,包括用户钱包、技师信息、项目信息、地址信息和订单金额等
+     *
+     * @param int $userId 用户ID
+     * @param array $data 订单数据
+     * @return array 返回初始化的订单信息
+     * @throws \Exception 初始化失败时抛出异常
      */
     public function initialize(int $userId, array $data): array
     {
@@ -96,80 +103,70 @@ class OrderService
      */
     public function createOrder(int $userId, array $data): array
     {
-        try {
-            return DB::transaction(function () use ($userId, $data) {
-                // 1. 参数校验
-                $user = MemberUser::where('id', $userId)
-                    ->where('state', 'enable')
-                    ->firstOrFail();
+        return DB::transaction(function () use ($userId, $data) {
+            // 1. 参数校验
+            $user = MemberUser::where('id', $userId)
+                ->where('state', 'enable')
+                ->firstOrFail();
 
-                $project = Project::where('id', $data['project_id'])
-                    ->where('state', 'enable')
-                    ->firstOrFail();
+            $project = Project::where('id', $data['project_id'])
+                ->where('state', 'enable')
+                ->firstOrFail();
 
-                // 2. 订单类型判断
-                $orderType = isset($data['order_id']) ? 'add_time' : 'normal';
+            // 2. 订单类型判断
+            $orderType = isset($data['order_id']) ? 'add_time' : 'normal';
 
-                // 关键操作:验证必要参数
-                abort_if(empty($data['project_id']), 400, '项目ID不能为空');
-                abort_if(empty($data['service_time']), 400, '服务时间不能为空');
-                abort_if($orderType == 'normal' && empty($data['coach_id']), 400, '技师ID不能为空');
-                abort_if($orderType == 'normal' && empty($data['address_id']), 400, '地址ID不能为空');
+            // 关键操作:验证必要参数
+            abort_if(empty($data['project_id']), 400, '项目ID不能为空');
+            abort_if(empty($data['service_time']), 400, '服务时间不能为空');
+            abort_if($orderType == 'normal' && empty($data['coach_id']), 400, '技师ID不能为空');
+            abort_if($orderType == 'normal' && empty($data['address_id']), 400, '地址ID不能为空');
 
-                // 3. 验证地址
-                $address = $user->addresses()
-                    ->where('id', $data['address_id'])
-                    ->firstOrFail();
+            // 3. 验证地址
+            $address = $user->addresses()
+                ->where('id', $data['address_id'])
+                ->firstOrFail();
 
-                // 4. 根据订单类型处理
-                if ($orderType == 'normal') {
-                    $coach = $this->validateCoach($data['coach_id']);
-                } else {
-                    $originalOrder = $this->getOriginalOrder($user, $data['order_id']);
-                    $coach = $this->validateCoach($originalOrder->coach_id);
-                    abort_if(! in_array($originalOrder->state, ['service_ing', 'service_end']), 400, '原订单状态不允许加钟');
-                    $data = $this->prepareAddTimeData($originalOrder, $data);
-                }
+            // 4. 根据订单类型处理
+            if ($orderType == 'normal') {
+                $coach = $this->validateCoach($data['coach_id']);
+            } else {
+                $originalOrder = $this->getOriginalOrder($user, $data['order_id']);
+                $coach = $this->validateCoach($originalOrder->coach_id);
+                abort_if(! in_array($originalOrder->state, ['service_ing', 'service_end']), 400, '原订单状态不允许加钟');
+                $data = $this->prepareAddTimeData($originalOrder, $data);
+            }
 
-                // 5. 计算订单金额
-                $amounts = $this->calculateOrderAmount(
-                    $userId,
-                    $address->id,
-                    $data['coach_id'],
-                    $data['project_id'],
-                    $project->agent_id,
-                    $data['use_balance'] ?? false
-                );
+            // 5. 计算订单金额
+            $amounts = $this->calculateOrderAmount(
+                $userId,
+                $address->id,
+                $data['coach_id'],
+                $data['project_id'],
+                $project->agent_id,
+                $data['use_balance'] ?? false
+            );
 
-                // 6. 验证金额和余额
-                abort_if($amounts['total_amount'] <= 0, 400, '订单金额异常');
-                if ($amounts['payment_type'] == 'balance') {
-                    $wallet = $user->wallet;
-                    abort_if($wallet->available_balance < $amounts['balance_amount'], 400, '可用余额不足');
-                }
+            // 6. 验证金额和余额
+            abort_if($amounts['total_amount'] <= 0, 400, '订单金额异常');
+            if ($amounts['payment_type'] == 'balance') {
+                $wallet = $user->wallet;
+                abort_if($wallet->available_balance < $amounts['balance_amount'], 400, '可用余额不足');
+            }
 
-                // 7. 创建订单记录
-                $order = $this->createOrderRecord($userId, $data, $orderType, $address, (object) $amounts);
+            // 7. 创建订单记录
+            $order = $this->createOrderRecord($userId, $data, $orderType, $address, (object) $amounts);
 
-                // 8. 余额支付处理
-                if ($order->payment_type == 'balance') {
-                    $this->handleBalancePayment($user, $order, $orderType);
-                }
+            // 8. 余额支付处理
+            if ($order->payment_type == 'balance') {
+                $this->handleBalancePayment($user, $order, $orderType);
+            }
 
-                return [
-                    'order_id' => $order->id,
-                    'payment_type' => $order->payment_type,
-                ];
-            });
-        } catch (Exception $e) {
-            Log::error('创建订单失败:', [
-                'message' => $e->getMessage(),
-                'user_id' => $userId,
-                'data' => $data,
-                'trace' => $e->getTraceAsString(),
-            ]);
-            throw $e;
-        }
+            return [
+                'order_id' => $order->id,
+                'payment_type' => $order->payment_type,
+            ];
+        });
     }
 
     // 提取方法:验证技师
@@ -177,9 +174,9 @@ class OrderService
     {
         $coach = CoachUser::where('id', $coachId)
             ->where('state', 'enable')
-            ->whereHas('info', fn ($q) => $q->where('state', 'approved'))
-            ->whereHas('qual', fn ($q) => $q->where('state', 'approved'))
-            ->whereHas('real', fn ($q) => $q->where('state', 'approved'))
+            ->whereHas('info', fn($q) => $q->where('state', 'approved'))
+            ->whereHas('qual', fn($q) => $q->where('state', 'approved'))
+            ->whereHas('real', fn($q) => $q->where('state', 'approved'))
             ->firstOrFail();
 
         return $coach;
@@ -214,7 +211,7 @@ class OrderService
     }
 
     // 提取方法:创建订单记录
-    private function createOrderRecord($userId, $data, $orderType, $address, $amounts): Order
+    private function createOrderRecord($userId, $data, $orderType, $address, object $amounts): Order
     {
         $order = new Order;
         $order->user_id = $userId;
@@ -263,9 +260,9 @@ class OrderService
             'remark' => '余额支付',
         ]);
 
-        $user->wallet->decrement('total_balance', $order->balance_amount);
-        $user->wallet->decrement('available_balance', $order->balance_amount);
-        $user->wallet->save();
+        $user->wallet->decrement('total_balance', $order->balance_amount)
+            ->decrement('available_balance', $order->balance_amount)
+            ->save();
     }
 
     /**
@@ -293,7 +290,6 @@ class OrderService
                 }
 
                 return ['message' => '订单已取消'];
-
             } catch (Exception $e) {
                 $this->logCancelOrderError($e, $userId, $orderId);
                 throw $e;
@@ -487,7 +483,6 @@ class OrderService
                 // event(new OrderFinishedEvent($order));
 
                 return ['message' => '订单已完成'];
-
             } catch (Exception $e) {
                 $this->logFinishOrderError($e, $userId, $orderId);
                 throw $e;
@@ -735,10 +730,10 @@ class OrderService
         try {
             // 1. 校验技师
             $coach = CoachUser::where('state', 'enable')
-                ->whereHas('info', fn ($q) => $q->where('state', 'approved'))
-                ->whereHas('real', fn ($q) => $q->where('state', 'approved'))
-                ->whereHas('qual', fn ($q) => $q->where('state', 'approved'))
-                ->with(['projects' => fn ($q) => $q->where('project_id', $projectId)])
+                ->whereHas('info', fn($q) => $q->where('state', 'approved'))
+                ->whereHas('real', fn($q) => $q->where('state', 'approved'))
+                ->whereHas('qual', fn($q) => $q->where('state', 'approved'))
+                ->with(['projects' => fn($q) => $q->where('project_id', $projectId)])
                 ->find($coachId);
 
             abort_if(! $coach, 404, '技师不存在或状态异常');
@@ -765,9 +760,8 @@ class OrderService
             return $coachProject->delivery_fee_type == 'round_trip'
                 ? bcmul($fee, '2', 2)
                 : $fee;
-
         } catch (Exception $e) {
-            Log::error(__CLASS__.'->'.__FUNCTION__.'计算路费失败:', [
+            Log::error(__CLASS__ . '->' . __FUNCTION__ . '计算路费失败:', [
                 'message' => $e->getMessage(),
                 'coach_id' => $coachId,
                 'project_id' => $projectId,
@@ -909,9 +903,8 @@ class OrderService
                 'project_amount' => $projectAmount,
                 'delivery_fee' => $deliveryFee,
             ];
-
         } catch (Exception $e) {
-            Log::error(__CLASS__.'->'.__FUNCTION__.'计算订单金额失败:', [
+            Log::error(__CLASS__ . '->' . __FUNCTION__ . '计算订单金额失败:', [
                 'message' => $e->getMessage(),
                 'user_id' => $userId,
                 'project_id' => $projectId,
@@ -1009,7 +1002,6 @@ class OrderService
                 }
 
                 return true;
-
             } catch (Exception $e) {
                 $this->logAssignCoachError($e, $userId, $orderId, $coachId);
                 throw $e;
@@ -1052,7 +1044,7 @@ class OrderService
         WalletPaymentRecord::create([
             'order_id' => $order->id,
             'wallet_id' => $wallet->id,
-            'payment_no' => 'balance_'.$order->id,
+            'payment_no' => 'balance_' . $order->id,
             'payment_method' => 'balance',
             'total_amount' => $order->balance_amount,
             'actual_amount' => 0,

+ 9 - 8
app/Services/Client/ProjectService.php

@@ -40,20 +40,21 @@ class ProjectService
     }
 
     /**
-     * 获取项目详情
+     * 如果代理商存在,则返回代理商项目,否则返回系统项目
+     *
+     * @param int $projectId 项目ID
+     * @param string $areaCode 区域代码
+     * @return Project 项目模型
+     * @throws \Illuminate\Http\Exceptions\HttpResponseException 项目不存在时抛出404异常
      */
     public function getProjectDetail($projectId, $areaCode)
     {
-        // 根据区域代码获取代理商
-        $agent = $this->findAvailableAgent($areaCode);
-
         // 查询系统项目
         $project = Project::where('state', 'enable')->find($projectId);
+        abort_if(! $project, 404, '项目不存在');
 
-        if (! $project) {
-            throw new \Exception('项目不存在');
-        }
-
+       // 根据区域代码获取代理商
+        $agent = $this->findAvailableAgent($areaCode);
         if ($agent) {
             // 查询代理商项目
             $project = $agent->projects()->where('project_id', $projectId)->first();