WIN-2308041133\Administrator 1 день тому
батько
коміт
a3fae61d43
2 змінених файлів з 93 додано та 133 видалено
  1. 63 96
      app/api/controller/Chat.php
  2. 30 37
      app/api/controller/ChatBuy.php

+ 63 - 96
app/api/controller/Chat.php

@@ -3,73 +3,69 @@ declare (strict_types = 1);
 
 namespace app\api\controller;
 
+use app\BaseController;
 use app\model\api\ChatRecord;
 use app\model\api\ChatUserRelation;
 use app\model\api\User;
+use app\Request;
 use app\services\chat\ChatBalanceService;
-use library\JwtAuth;
-use library\LoginSession;
-use think\Request;
-use think\Response;
 
 /**
  * 聊天控制器
  */
-class Chat extends JwtAuth
+class Chat extends BaseController
 {
-    protected $noNeedLogin = ['recordList'];
-    
     /**
      * 获取会话列表
-     * @return Response
      */
-    public function sessionList(): Response
+    public function sessionList(Request $request)
     {
-        $sessions = ChatUserRelation::getUserSessions($this->userId);
+        $userId = $request->user['uid'];
+        $sessions = ChatUserRelation::getUserSessions($userId);
         
-        return $this->success('获取成功', [
+        return app('json')->success('获取成功', [
             'list' => $sessions,
         ]);
     }
     
     /**
      * 初始化会话(首次聊天扣次数)
-     * @return Response
      */
-    public function initSession(): Response
+    public function initSession(Request $request)
     {
-        $data = $this->request->post();
+        $data = $request->post();
         $toUserId = (int)($data['to_user_id'] ?? 0);
+        $userId = $request->user['uid'];
         
         if ($toUserId <= 0) {
-            return $this->fail('对方用户ID错误');
+            return app('json')->fail('对方用户ID错误');
         }
         
-        if ($toUserId == $this->userId) {
-            return $this->fail('不能和自己聊天');
+        if ($toUserId == $userId) {
+            return app('json')->fail('不能和自己聊天');
         }
         
         // 检查对方用户是否存在
         $toUser = User::find($toUserId);
         if (!$toUser) {
-            return $this->fail('用户不存在');
+            return app('json')->fail('用户不存在');
         }
         
         // 创建或获取会话关系
-        $relation = ChatUserRelation::getOrCreate($this->userId, $toUserId);
+        $relation = ChatUserRelation::getOrCreate($userId, $toUserId);
         
         // 如果未扣过次数,则扣除
         if ($relation && $relation->is_deduct == ChatUserRelation::NOT_DEDUCT) {
-            $result = ChatBalanceService::checkAndDeductFirstChat($this->userId, $toUserId);
+            $result = ChatBalanceService::checkAndDeductFirstChat($userId, $toUserId);
             
             if (!$result['success']) {
-                return $this->fail($result['message']);
+                return app('json')->fail($result['message']);
             }
         }
         
-        $balance = ChatBalanceService::getBalance($this->userId);
+        $balance = ChatBalanceService::getBalance($userId);
         
-        return $this->success('会话创建成功', [
+        return app('json')->success('会话创建成功', [
             'to_user_id' => $toUserId,
             'to_nickname' => $toUser->nickname ?? '',
             'to_avatar' => $toUser->avatar ?? '',
@@ -79,15 +75,15 @@ class Chat extends JwtAuth
     
     /**
      * 发送消息
-     * @return Response
      */
-    public function send(): Response
+    public function send(Request $request)
     {
-        $data = $this->request->post();
+        $data = $request->post();
         $toUserId = (int)($data['to_user_id'] ?? 0);
         $content = trim($data['content'] ?? '');
         $type = (int)($data['type'] ?? ChatRecord::TYPE_TEXT);
         $formType = (int)($data['form_type'] ?? ChatRecord::FROM_PC);
+        $userId = $request->user['uid'];
         
         // 验证 form_type 有效值
         if (!in_array($formType, [ChatRecord::FROM_PC, ChatRecord::FROM_WECHAT, ChatRecord::FROM_MINIAPP, ChatRecord::FROM_H5])) {
@@ -95,56 +91,42 @@ class Chat extends JwtAuth
         }
         
         if ($toUserId <= 0) {
-            return $this->fail('对方用户ID错误');
+            return app('json')->fail('对方用户ID错误');
         }
         
         if (empty($content) && $type == ChatRecord::TYPE_TEXT) {
-            return $this->fail('消息内容不能为空');
+            return app('json')->fail('消息内容不能为空');
         }
         
-        if ($toUserId == $this->userId) {
-            return $this->fail('不能和自己聊天');
+        if ($toUserId == $userId) {
+            return app('json')->fail('不能和自己聊天');
         }
         
         // 检查对方用户是否存在
         $toUser = User::find($toUserId);
         if (!$toUser) {
-            return $this->fail('用户不存在');
+            return app('json')->fail('用户不存在');
         }
         
         // 检查会话关系是否存在,不存在则创建
-        $relation = ChatUserRelation::getOrCreate($this->userId, $toUserId);
+        $relation = ChatUserRelation::getOrCreate($userId, $toUserId);
         
         // 如果未扣过次数,则扣除
         if ($relation && $relation->is_deduct == ChatUserRelation::NOT_DEDUCT) {
-            $result = ChatBalanceService::checkAndDeductFirstChat($this->userId, $toUserId);
+            $result = ChatBalanceService::checkAndDeductFirstChat($userId, $toUserId);
             
             if (!$result['success']) {
-                return $this->fail($result['message']);
+                return app('json')->fail($result['message']);
             }
         }
         
         // 保存聊天记录(包含来源类型)
-        $record = ChatRecord::saveRecord($this->userId, $toUserId, $content, $type, $formType);
+        $record = ChatRecord::saveRecord($userId, $toUserId, $content, $type, $formType);
         
         // 更新会话关系时间
         ChatUserRelation::where('id', $relation->id)->update(['update_time' => time()]);
         
-        // 广播消息给在线用户
-        self::broadcastMessage($toUserId, [
-            'type' => 'new_message',
-            'data' => [
-                'id' => $record->id,
-                'from_user_id' => $this->userId,
-                'to_user_id' => $toUserId,
-                'content' => $content,
-                'msg_type' => $type,
-                'form_type' => $formType,
-                'create_time' => $record->create_time,
-            ],
-        ]);
-        
-        return $this->success('发送成功', [
+        return app('json')->success('发送成功', [
             'record_id' => $record->id,
             'create_time' => $record->create_time,
         ]);
@@ -152,128 +134,113 @@ class Chat extends JwtAuth
     
     /**
      * 获取聊天记录
-     * @return Response
      */
-    public function recordList(): Response
+    public function recordList(Request $request)
     {
-        $data = $this->request->get();
+        $data = $request->get();
         $toUserId = (int)($data['to_user_id'] ?? 0);
         $page = (int)($data['page'] ?? 1);
         $limit = (int)($data['limit'] ?? 20);
+        $userId = $request->user['uid'];
         
         if ($toUserId <= 0) {
-            return $this->fail('对方用户ID错误');
+            return app('json')->fail('对方用户ID错误');
         }
         
-        $result = ChatRecord::getChatRecords($this->userId, $toUserId, $page, $limit);
+        $result = ChatRecord::getChatRecords($userId, $toUserId, $page, $limit);
         
         // 处理消息类型文本
         foreach ($result['list'] as &$item) {
             $item['type_text'] = ChatRecord::getTypeText($item['type']);
             $item['form_type_text'] = ChatRecord::getFormTypeText($item['form_type'] ?? 0);
             // 判断是否是自己发送的
-            $item['is_mine'] = $item['user_id'] == $this->userId;
+            $item['is_mine'] = $item['user_id'] == $userId;
         }
         
-        return $this->success('获取成功', $result);
+        return app('json')->success('获取成功', $result);
     }
     
     /**
      * 标记消息已读
-     * @return Response
      */
-    public function markRead(): Response
+    public function markRead(Request $request)
     {
-        $data = $this->request->post();
+        $data = $request->post();
         $fromUserId = (int)($data['from_user_id'] ?? 0);
+        $userId = $request->user['uid'];
         
         if ($fromUserId <= 0) {
-            return $this->fail('用户ID错误');
+            return app('json')->fail('用户ID错误');
         }
         
-        ChatRecord::markAsRead($this->userId, $fromUserId);
+        ChatRecord::markAsRead($userId, $fromUserId);
         
-        return $this->success('标记成功');
+        return app('json')->success('标记成功');
     }
     
     /**
      * 获取未读消息数
-     * @return Response
      */
-    public function unreadCount(): Response
+    public function unreadCount(Request $request)
     {
-        $data = $this->request->get();
+        $data = $request->get();
         $fromUserId = $data['from_user_id'] ?? null;
+        $userId = $request->user['uid'];
         
         if ($fromUserId !== null) {
-            $count = ChatRecord::getUnreadCount($this->userId, (int)$fromUserId);
+            $count = ChatRecord::getUnreadCount($userId, (int)$fromUserId);
         } else {
-            $count = ChatRecord::getTotalUnreadCount($this->userId);
+            $count = ChatRecord::getTotalUnreadCount($userId);
         }
         
-        return $this->success('获取成功', [
+        return app('json')->success('获取成功', [
             'count' => $count,
         ]);
     }
     
     /**
      * 删除会话
-     * @return Response
      */
-    public function deleteSession(): Response
+    public function deleteSession(Request $request)
     {
-        $data = $this->request->post();
+        $data = $request->post();
         $toUserId = (int)($data['to_user_id'] ?? 0);
+        $userId = $request->user['uid'];
         
         if ($toUserId <= 0) {
-            return $this->fail('对方用户ID错误');
+            return app('json')->fail('对方用户ID错误');
         }
         
-        $result = ChatUserRelation::deleteSession($this->userId, $toUserId);
+        $result = ChatUserRelation::deleteSession($userId, $toUserId);
         
         if ($result) {
-            return $this->success('删除成功');
+            return app('json')->success('删除成功');
         }
         
-        return $this->fail('删除失败');
+        return app('json')->fail('删除失败');
     }
     
     /**
      * 获取用户信息
-     * @return Response
      */
-    public function getUserInfo(): Response
+    public function getUserInfo(Request $request)
     {
-        $data = $this->request->get();
+        $data = $request->get();
         $userId = (int)($data['user_id'] ?? 0);
         
         if ($userId <= 0) {
-            return $this->fail('用户ID错误');
+            return app('json')->fail('用户ID错误');
         }
         
         $user = User::find($userId);
         if (!$user) {
-            return $this->fail('用户不存在');
+            return app('json')->fail('用户不存在');
         }
         
-        return $this->success('获取成功', [
+        return app('json')->success('获取成功', [
             'user_id' => $user->id,
             'nickname' => $user->nickname ?? '',
             'avatar' => $user->avatar ?? '',
         ]);
     }
-    
-    /**
-     * 广播消息给指定用户
-     * @param int $userId 用户ID
-     * @param array $data 消息数据
-     */
-    protected static function broadcastMessage(int $userId, array $data): void
-    {
-        try {
-            \Channel\Client::getInstance()->send('muyinjie_chat_' . $userId, $data);
-        } catch (\Throwable $e) {
-            // 忽略广播失败
-        }
-    }
 }

+ 30 - 37
app/api/controller/ChatBuy.php

@@ -3,30 +3,26 @@ declare (strict_types = 1);
 
 namespace app\api\controller;
 
+use app\BaseController;
 use app\model\api\ChatBalanceLog;
 use app\model\api\ChatOrder;
+use app\Request;
 use app\services\chat\ChatBalanceService;
-use library\Helper;
-use library\JwtAuth;
-use think\Response;
 
 /**
  * 聊天次数购买控制器
  */
-class ChatBuy extends JwtAuth
+class ChatBuy extends BaseController
 {
-    protected $noNeedLogin = [];
-    
     /**
      * 获取购买配置信息
-     * @return Response
      */
-    public function config(): Response
+    public function config(Request $request)
     {
         $price = ChatBalanceService::getBuyPrice();
-        $balance = ChatBalanceService::getBalance($this->userId);
+        $balance = ChatBalanceService::getBalance($request->user['uid']);
         
-        return $this->success('获取成功', [
+        return app('json')->success('获取成功', [
             'price' => $price,           // 单次购买价格(积分)
             'balance' => $balance,      // 当前剩余次数
         ]);
@@ -34,52 +30,52 @@ class ChatBuy extends JwtAuth
     
     /**
      * 创建购买订单
-     * @return Response
      */
-    public function createOrder(): Response
+    public function createOrder(Request $request)
     {
-        $data = $this->request->post();
+        $data = $request->post();
         $chatNum = (int)($data['chat_num'] ?? 1);
+        $userId = $request->user['uid'];
         
         if ($chatNum <= 0) {
-            return $this->fail('购买数量必须大于0');
+            return app('json')->fail('购买数量必须大于0');
         }
         
         $price = ChatBalanceService::getBuyPrice();
         if ($price <= 0) {
-            return $this->fail('购买价格未设置');
+            return app('json')->fail('购买价格未设置');
         }
         
         $totalPrice = $price * $chatNum;
         
         // 检查用户积分是否足够
-        $userScore = \app\model\api\UserScoreDetail::getUserScore($this->userId);
+        $userScore = \app\model\api\UserScoreDetail::getUserScore($userId);
         if ($userScore < $totalPrice) {
-            return $this->fail('积分不足,当前积分:' . $userScore);
+            return app('json')->fail('积分不足,当前积分:' . $userScore);
         }
         
         // 创建订单
-        $order = ChatOrder::createOrder($this->userId, $chatNum, $totalPrice);
+        $order = ChatOrder::createOrder($userId, $chatNum, $totalPrice);
         
         if (!$order) {
-            return $this->fail('订单创建失败');
+            return app('json')->fail('订单创建失败');
         }
         
         // 立即支付(积分支付,无需跳转)
-        $result = ChatBalanceService::buyWithScore($this->userId, $chatNum, $order);
+        $result = ChatBalanceService::buyWithScore($userId, $chatNum, $order);
         
         if (!$result) {
             // 支付失败,取消订单
             ChatOrder::cancelOrder($order->id);
-            return $this->fail('支付失败');
+            return app('json')->fail('支付失败');
         }
         
         // 更新订单状态
         ChatOrder::paySuccess($order->id);
         
-        $newBalance = ChatBalanceService::getBalance($this->userId);
+        $newBalance = ChatBalanceService::getBalance($userId);
         
-        return $this->success('购买成功', [
+        return app('json')->success('购买成功', [
             'order_id' => $order->id,
             'order_no' => $order->order_no,
             'chat_num' => $chatNum,
@@ -90,49 +86,46 @@ class ChatBuy extends JwtAuth
     
     /**
      * 获取当前聊天次数余额
-     * @return Response
      */
-    public function balance(): Response
+    public function balance(Request $request)
     {
-        $balance = ChatBalanceService::getBalance($this->userId);
+        $balance = ChatBalanceService::getBalance($request->user['uid']);
         
-        return $this->success('获取成功', [
+        return app('json')->success('获取成功', [
             'balance' => $balance,
         ]);
     }
     
     /**
      * 获取购买记录列表
-     * @return Response
      */
-    public function orderList(): Response
+    public function orderList(Request $request)
     {
-        $data = $this->request->get();
+        $data = $request->get();
         $page = (int)($data['page'] ?? 1);
         $limit = (int)($data['limit'] ?? 10);
         
-        $result = ChatOrder::getUserOrders($this->userId, $page, $limit);
+        $result = ChatOrder::getUserOrders($request->user['uid'], $page, $limit);
         
         // 处理订单状态文本
         foreach ($result['list'] as &$item) {
             $item['status_text'] = ChatOrder::getStatusText($item['status']);
         }
         
-        return $this->success('获取成功', $result);
+        return app('json')->success('获取成功', $result);
     }
     
     /**
      * 获取变动明细列表
-     * @return Response
      */
-    public function balanceLogList(): Response
+    public function balanceLogList(Request $request)
     {
-        $data = $this->request->get();
+        $data = $request->get();
         $page = (int)($data['page'] ?? 1);
         $limit = (int)($data['limit'] ?? 10);
         
-        $result = ChatBalanceLog::getUserLogs($this->userId, $page, $limit);
+        $result = ChatBalanceLog::getUserLogs($request->user['uid'], $page, $limit);
         
-        return $this->success('获取成功', $result);
+        return app('json')->success('获取成功', $result);
     }
 }