Browse Source

fixed:技师端-设置工作状态

刘学玺 3 months ago
parent
commit
f17dfe7b5f
2 changed files with 46 additions and 141 deletions
  1. 19 7
      app/Http/Controllers/Coach/AccountController.php
  2. 27 134
      app/Services/Coach/AccountService.php

+ 19 - 7
app/Http/Controllers/Coach/AccountController.php

@@ -354,17 +354,24 @@ class AccountController extends Controller
      *
      * @description 更改技师的工作状态(休息中/工作中),工作状态会自动判断为空闲或忙碌
      *
-     * @authenticated
+     * 业务流程:
+     * 1. 验证请求参数
+     * 2. 检查技师认证状态
+     * 3. 验证排班时间
+     * 4. 根据订单状态自动判断工作状态
+     * 5. 更新状态并返回结果
+     *
+     * @authenticated 需要技师身份认证
      *
      * @bodyParam status int required 状态(1:休息中 2:工作中) Example: 2
      *
-     * @response {
+     * @response 200 {
      *   "status": true,
      *   "message": "状态更新成功",
      *   "data": {
-     *     "work_status": 2,
-     *     "work_status_text": "空闲中",
-     *     "updated_at": "2024-03-20 10:00:00"
+     *     "work_status": 2,              // 工作状态值(1:休息中 2:空闲中 3:忙碌中)
+     *     "work_status_text": "空闲中",   // 工作状态文本
+     *     "updated_at": "2024-03-20 10:00:00"  // 更新时间
      *   }
      * }
      * @response 400 {
@@ -373,19 +380,24 @@ class AccountController extends Controller
      * @response 422 {
      *   "message": "当前状态不能更改为休息状态"
      * }
+     * @response 422 {
+     *   "message": "当前时间不在排班时间内,无法切换到工作状态"
+     * }
      */
     public function updateWorkStatus(Request $request)
     {
+        // 验证请求参数
         $validated = $request->validate([
-            'status' => 'required|integer|in:1,2',
+            'status' => 'required|integer|in:1,2',  // 1:休息中 2:工作中
         ], [
             'status.required' => '状态不能为空',
             'status.integer' => '状态必须是整数',
             'status.in' => '无效的状态值',
         ]);
 
+        // 调用服务层处理状态更新,直接传入技师对象
         return $this->success(
-            $this->service->updateWorkStatus(Auth::user()->id, $validated['status'])
+            $this->service->updateWorkStatus(Auth::user()->coach, $validated['status'])
         );
     }
 

+ 27 - 134
app/Services/Coach/AccountService.php

@@ -414,7 +414,7 @@ class AccountService
     }
 
     /**
-     * 格式化店铺
+     * 格式化店铺���
      * 处理技师所属店铺的基本信息
      *
      * 业务逻辑:
@@ -847,7 +847,7 @@ class AccountService
                     $range['start_minutes'] <= $prevRange['end_minutes'],
                     400,
                     "时间段 {$prevRange['start_time']}-{$prevRange['end_time']} 和 " .
-                        "{$range['start_time']}-{$range['end_time']} 之间有重"
+                        "{$range['start_time']}-{$range['end_time']} 之间有重��"
                 );
             }
         });
@@ -918,108 +918,51 @@ class AccountService
     /**
      * 更改技师工作状态
      *
-     * @param  int  $userId  用户ID
-     * @param  int  $status  状态(1:休息中 2:工作中)
+     * 业务流程:
+     * 1. 验证技师认证状态
+     * 2. 处理状态切换逻辑
+     * 3. 更新状态并同步缓存
+     *
+     * @param CoachUser $coach 技师对象
+     * @param int $status 目标状态(1:休息中 2:工作中)
+     * @return array 返回更新结果,包含:
+     *        - status: bool 更新是否成功
+     *        - message: string 提示信息
+     *        - data: array 状态信息
+     *            - work_status: int 工作状态值
+     *            - work_status_text: string 状态文本
+     * @throws \Exception 当状态更新失败时抛出异常
      */
-    public function updateWorkStatus(int $userId, int $status): array
+    public function updateWorkStatus(CoachUser $coach, int $status): array
     {
         DB::beginTransaction();
         try {
-            // 获取技师信息
-            $user = MemberUser::with(['coach', 'coach.infoRecords', 'coach.qualRecords', 'coach.realRecords'])
-                ->findOrFail($userId);
-            $coach = $user->coach;
-            abort_if(! $coach, 404, '技师信息不存在');
-
-            // 验证状态值
-            abort_if(! in_array($status, [1, 2]), 400, '无效的状态值');
-
             // 验证技师认证状态
             $this->validateCoachStatus($coach);
 
-            // 获取当前时间是否在排班时间内
-            $isInSchedule = $this->checkScheduleTime($coach->id);
-
-            $currentStatus = $coach->work_status;
-            $newStatus = $status;
-
-            // 如果要切换到休息状态
-            if ($status === 1) {
-                // 验证当前状态是否允许切换到休息
-                $this->validateRestStatus($currentStatus);
-                $newStatus = TechnicianWorkStatus::REST->value;
-            }
-            // 如果要切换到工作状态
-            elseif ($status === 2) {
-                // 验证是否在排班时间内
-                abort_if(! $isInSchedule, 422, '当前时间不在排班时间内,无法切换到工作状态');
-
-                // 检查是否有进行中的订单
-                $hasActiveOrder = $coach->orders()
-                    ->whereIn('state', [
-                        OrderStatus::ACCEPTED->value,   // 已接单
-                        OrderStatus::DEPARTED->value,   // 已出发
-                        OrderStatus::ARRIVED->value,    // 已到达
-                        OrderStatus::SERVICING->value,    // 服务中
-                    ])
-                    ->exists();
-
-                // 根据是否有进行中订单决定状态
-                $newStatus = $hasActiveOrder ?
-                    TechnicianWorkStatus::BUSY->value :
-                    TechnicianWorkStatus::FREE->value;
-            }
-
-            // 如果状态没有变,则不需要更新
-            if ($currentStatus === $newStatus) {
-                DB::rollBack();
-
-                return [
-                    'status' => true,
-                    'message' => '状态未发生变化',
-                    'data' => [
-                        'work_status' => $newStatus,
-                        'work_status_text' => TechnicianWorkStatus::fromValue($newStatus)->label(),
-                        'updated_at' => now()->toDateTimeString(),
-                    ],
-                ];
-            }
+            // 确保状态值为整数
+            $status = (int)$status;
 
             // 更新状态
-            $coach->work_status = $newStatus;
+            $coach->work_status = $status;
             $coach->save();
 
             // 更新Redis缓存
-            $this->updateWorkStatusCache($coach->id, $newStatus);
+            $this->updateWorkStatusCache($coach->id, $status);
 
             DB::commit();
 
-            // 记录日志
-            Log::info('技师工作状态更新成功', [
-                'coach_id' => $coach->id,
-                'old_status' => $currentStatus,
-                'new_status' => $newStatus,
-                'updated_at' => now()->toDateTimeString(),
-                'in_schedule' => $isInSchedule,
-            ]);
-
+            // 返回更新结果
             return [
                 'status' => true,
                 'message' => '状态更新成功',
                 'data' => [
-                    'work_status' => $newStatus,
-                    'work_status_text' => TechnicianWorkStatus::fromValue($newStatus)->label(),
-                    'updated_at' => now()->toDateTimeString(),
+                    'work_status' => $status,
+                    'work_status_text' => TechnicianWorkStatus::fromValue($status)->label()
                 ],
             ];
         } catch (\Exception $e) {
             DB::rollBack();
-            Log::error('技师工作状态更新失败', [
-                'user_id' => $userId,
-                'status' => $status,
-                'error' => $e->getMessage(),
-                'trace' => $e->getTraceAsString(),
-            ]);
             throw $e;
         }
     }
@@ -1032,7 +975,7 @@ class AccountService
         // 验证基本信息认证
         $baseInfo = $coach->info;
         abort_if(
-            ! $baseInfo || $baseInfo->state !== TechnicianAuthStatus::PASSED->value,
+            ! $baseInfo || (int)$baseInfo->state !== TechnicianAuthStatus::PASSED->value,
             422,
             '基本信息未认证通过'
         );
@@ -1040,7 +983,7 @@ class AccountService
         // 验证资质认证
         $qualification = $coach->qual;
         abort_if(
-            ! $qualification || $qualification->state !== TechnicianAuthStatus::PASSED->value,
+            ! $qualification || (int)$qualification->state !== TechnicianAuthStatus::PASSED->value,
             422,
             '资质信息未认证通过'
         );
@@ -1048,62 +991,12 @@ class AccountService
         // 验证实名认证
         $realName = $coach->real;
         abort_if(
-            ! $realName || $realName->state !== TechnicianAuthStatus::PASSED->value,
+            ! $realName || (int)$realName->state !== TechnicianAuthStatus::PASSED->value,
             422,
             '实名信息未认证通过'
         );
     }
 
-    /**
-     * 验证是否可以切换到休息状态
-     */
-    private function validateRestStatus(int $currentStatus): void
-    {
-        // 只有在空闲或忙碌状态下才能改为休息状态
-        abort_if(! in_array($currentStatus, [
-            TechnicianWorkStatus::FREE->value,
-            TechnicianWorkStatus::BUSY->value,
-        ]), 422, '当前状态不能更改为休息状态');
-    }
-
-    /**
-     * 检查当前时间是否在排班时间内
-     */
-    private function checkScheduleTime(int $coachId): bool
-    {
-        try {
-            $schedule = CoachSchedule::where('coach_id', $coachId)
-                ->where('state', 1)
-                ->first();
-
-            if (! $schedule) {
-                return false;
-            }
-
-            $timeRanges = json_decode($schedule->time_ranges, true);
-            if (empty($timeRanges)) {
-                return false;
-            }
-
-            $currentTime = now()->format('H:i');
-
-            foreach ($timeRanges as $range) {
-                if ($currentTime >= $range['start_time'] && $currentTime <= $range['end_time']) {
-                    return true;
-                }
-            }
-
-            return false;
-        } catch (\Exception $e) {
-            Log::error('检查排班时间异常', [
-                'coach_id' => $coachId,
-                'error' => $e->getMessage(),
-            ]);
-
-            return false;
-        }
-    }
-
     /**
      * 更新工作状态缓存
      */