Parcourir la source

Merge branch 'zhongqi-chat'

shish il y a 1 an
Parent
commit
01ae261a41

+ 0 - 1
app-hd/controllers/CategoryController.php

@@ -5,7 +5,6 @@ namespace hd\controllers;
 use bizHd\goods\classes\CategoryClass;
 use bizHd\goods\classes\GoodsCategoryClass;
 use bizHd\goods\services\CategoryService;
-use bizHd\goods\services\GoodsCategoryService;
 use Yii;
 use common\components\util;
 

+ 26 - 1
app-hd/controllers/ChatController.php

@@ -14,7 +14,6 @@ use GatewayClient\Gateway;
 
 class ChatController extends BaseController
 {
-
     //聊天 ssh 2019.12.28
     public function actionIndex()
     {
@@ -144,4 +143,30 @@ class ChatController extends BaseController
         util::success($respond);
     }
 
+
+    // ----------------------------  新聊天功能的接口  ----------------------------------
+    //最近聊天人
+    public function actionLatestUsers()
+    {
+        $respond = ChatService::getLatestUsers($this->shopId);
+        util::success($respond);
+    }
+
+    //聊天的内容
+    public function actionChatHistory()
+    {
+        $roomName = Yii::$app->request->post('roomName');
+        // 校验 $roomeName 的值,防止越权访问他人数据
+
+        $roomName = 'room_messages:' . $roomName;
+        $respond = \bizHd\message\services\ChatService::getChatHistory($roomName);
+        util::success($respond);
+    }
+
+    //门店的未读消息总数
+    public function actionUnReadMsgCount()
+    {
+        $c = ChatService::getUnReadMsgCount($this->shopId, 'message');
+        util::success(['msg_count'=>$c]);
+    }
 }

+ 1 - 0
app-mall/controllers/BaseController.php

@@ -31,6 +31,7 @@ class BaseController extends PublicController
                 util::fail('请先登录哈');
             }
         }
+        $userId = intval($userId);
         $this->userId = $userId;
         $user = UserClass::getById($userId, true);
         if (empty($user)) {

+ 30 - 0
app-mall/controllers/CategoryController.php

@@ -51,6 +51,7 @@ class CategoryController extends BaseController
         if (empty($user)) {
             util::success(['list' => []]);
         }
+
         $get = Yii::$app->request->get();
         $shop = $this->shop;
         $custom = $this->custom;
@@ -58,4 +59,33 @@ class CategoryController extends BaseController
         util::success($data);
     }
 
+
+    //无价格商品列表
+    public function actionNonPriceGoodsList()
+    {
+        $user = $this->user;
+        if (empty($user)) {
+            util::success(['list' => []]);
+        }
+
+        $where = [];
+        $goodsCond = [];
+        $get = Yii::$app->request->get();
+        $categoryId = isset($get['categoryId']) ? intval($get['categoryId']) : 0;
+        if ($categoryId != 0) {
+            $where['cId'] = $categoryId;
+        }
+        $where['mainId'] = $this->mainId;
+        //$where['delStatus'] = 0;//只获取非删除状态
+        //$where['status'] = 1;//上下架状态为1(正常)
+
+        $searchText = $get['searchText'] ?? '';
+        if (!empty($searchText)) {
+            $where['name'] = ['like', $searchText];
+        }
+        $goodsCond['priceType'] = 0;//限定查询的是无价格商品
+
+        $data = GoodsCategoryService::getGoodsList($where, $goodsCond);
+        util::success($data);
+    }
 }

+ 25 - 0
app-mall/controllers/ChatController.php

@@ -110,4 +110,29 @@ class ChatController extends BaseController
         util::success($respond);
     }
 
+    // ----------------------------  新聊天功能的接口  ----------------------------------
+    //最近聊天人
+    public function actionLatestUsers()
+    {
+        $respond = ChatService::getLatestUsers(intval($this->userId));
+        util::success($respond);
+    }
+
+    //聊天的内容
+    public function actionChatHistory()
+    {
+        $roomName = Yii::$app->request->post('roomName');
+        // 校验 $roomeName 的值,防止越权访问他人数据
+
+        $roomName = 'room_messages:' . $roomName;
+        $respond = ChatService::getChatHistory($roomName);
+        util::success($respond);
+    }
+
+    //客户的未读消息总数
+    public function actionUnReadMsgCount()
+    {
+        $c = ChatService::getUnReadMsgCount(intval($this->userId), 'message');
+        util::success(['msg_count'=>$c]);
+    }
 }

+ 1 - 0
app-mall/controllers/GoodsController.php

@@ -35,6 +35,7 @@ class GoodsController extends BaseController
             $picText  = PicTextClass::getById($picTextId, true);
             $info['picText'] = $picText;
         }
+        $info['customId'] = $this->customId;
 
         util::success($info);
     }

+ 9 - 1
biz-hd/message/classes/ChatClass.php

@@ -5,9 +5,9 @@ namespace bizHd\message\classes;
 use Yii;
 use bizHd\base\classes\BaseClass;
 
+// 只是 redis 模型(与 mysql 无关)
 class ChatClass extends BaseClass
 {
-
     //取有新消息客户的缓存键名 2019.12.29
     public static function getUnReplyUserKey($mainId)
     {
@@ -26,6 +26,7 @@ class ChatClass extends BaseClass
         return "merchantRecentlyUser" . $mainId;
     }
 
+    //获取消息的键
     public static function getMessageKey($useId)
     {
         return 'MerchantMessage' . $useId;
@@ -39,4 +40,11 @@ class ChatClass extends BaseClass
         return is_numeric($respond) ? $respond : 0;
     }
 
+    // ----------------- 新建的 获取键的方法(参考上面的得来)----------------------
+    //最近联系人列表的键
+    public static function getLatestUsersKey($shopId)
+    {
+        return "shop_chats:" . $shopId;
+    }
+
 }

+ 111 - 0
biz-hd/message/services/ChatService.php

@@ -3,7 +3,9 @@
 namespace bizHd\message\services;
 
 use bizHd\base\services\BaseService;
+use bizHd\custom\classes\CustomClass;
 use bizHd\message\classes\ChatClass;
+use bizHd\user\classes\UserClass;
 use bizHd\user\services\UserService;
 use common\components\arrayUtil;
 use Yii;
@@ -153,4 +155,113 @@ class ChatService extends BaseService
         return $data;
     }
 
+    // ------------------------------------------------  以下是新增的聊天方法  ------------------------------------------------
+    //最近聊天人(人:可能是客户,也可能是商家)
+    public static function getLatestUsers($shopId)
+    {
+        $cacheKey = ChatClass::getLatestUsersKey($shopId);
+        //返回有序集合,从高分到低分排序
+        $return = Yii::$app->redis->executeCommand('ZREVRANGE', [$cacheKey, 0, -1, 'WITHSCORES']);
+        if (empty($return)) {
+            return [];
+        }
+        $i = 0;
+        $arr = [];
+        foreach ($return as $key => $val) {
+            if ($key % 2 == 0) {
+                $arr[$i]['cId'] = $val;
+            } else {
+                $arr[$i]['score'] = $val;
+                $i++;
+            }
+        }
+        $userData = [];
+        //组合出最后聊天时间和未读消息数
+        foreach ($arr as $val) {
+            $customId = $val['cId'];
+            $score = floatval($val['score']);
+            $decimalPart = $score - floor($score);
+            $unReadNum = intval($decimalPart * 10000 + 0.5);// 加0.5 -- 使用四舍五入来处理浮点数精度问题
+            $time = intval($val['score']);
+            $date = date("Y-m-d H:i", $time);
+
+            $userData[$customId] = ['time' => $date, 'unReadNum' => $unReadNum];
+        }
+        $ids = array_column($arr, 'cId');
+        $infoList = CustomClass::getByIds($ids, null, null, 'id,name,mobile,avatar,shopId,userId');
+        foreach ($infoList as $customId => $info) {
+            $infoList[$customId]['unReadNum'] = isset($userData[$info['id']]['unReadNum']) ? $userData[$info['id']]['unReadNum'] : 0;
+            $infoList[$customId]['chatTime'] = isset($userData[$info['id']]['time']) ? $userData[$info['id']]['time'] : 0;
+        }
+        $infoList = arrayUtil::arraySort($infoList, 'chatTime', SORT_DESC);
+        return array_values($infoList);
+    }
+
+    public static function getChatHistory($roomName)
+    {
+        if (empty($roomName)) {
+            return [];
+        }
+        try {
+            $re = Yii::$app->redis;
+            $list = Yii::$app->redis->executeCommand('LRANGE', [$roomName, 0, -1]);
+            if (empty($list)) {
+                return [];
+            }
+            $result = [];
+            foreach ($list as $item) {
+                $decoded = json_decode($item, true);
+                $struct = (json_last_error() === JSON_ERROR_NONE) ? $decoded : $item;
+                $content = $struct['content'];
+                $message = json_decode($content, true);
+                $result[] = json_decode($message['message'], true);
+            }
+            return $result;
+        } catch (\Throwable $e) {
+            Yii::error('getChatHistory redis error: ' . $e->getMessage(), __METHOD__);
+            return [];
+        }
+    }
+
+    /**
+     * @param int $shopId 门店id
+     * @param string $unit 单位分:个数(person)消息(message)
+     * @return int
+     */
+    public static function getUnReadMsgCount($shopId, $unit='person')
+    {
+        $cacheKey = ChatClass::getLatestUsersKey($shopId);
+        //返回有序集合,从高分到低分排序
+        $return = Yii::$app->redis->executeCommand('ZREVRANGE', [$cacheKey, 0, -1, 'WITHSCORES']);
+        if (empty($return)) {
+            return 0;
+        }
+        $i = 0;
+        $arr = [];
+        foreach ($return as $key => $val) {
+            if ($key % 2 == 0) {
+                $arr[$i]['cId'] = $val;//customerId
+            } else {
+                $arr[$i]['score'] = $val;
+                $i++;
+            }
+        }
+
+        $msgCount = 0;
+        foreach ($arr as $val) {
+            //$customId = $val['cId'];
+            $score = floatval($val['score']);
+            $decimalPart = $score - floor($score);
+            $unReadNum = intval($decimalPart * 10000 + 0.5); // 加0.5 -- 使用四舍五入来处理浮点数精度问题
+
+            //根据未读消息数的单位进行计算总数
+            if ($unit == 'person'){
+                $msgCount += ($unReadNum >= 1 ? 1 : 0);
+            } else if ($unit == 'message'){
+                $msgCount += $unReadNum;
+            }
+        }
+
+        return $msgCount;
+    }
 }

+ 12 - 3
biz-mall/goods/services/GoodsCategoryService.php

@@ -12,8 +12,13 @@ class GoodsCategoryService extends BaseService
 
     public static $baseFile = '\bizMall\goods\classes\GoodsCategoryClass';
 
-    //查询一个分类下的商品,有分页 ssh 2019.12.2
-    public static function getGoodsList($where)
+    /**
+     * 查询一个分类下的商品,有分页
+     * @param array $where
+     * @param array $goodsCondition
+     * @return mixed
+     */
+    public static function getGoodsList($where, $goodsCondition = [])
     {
         $data = GoodsCategoryClass::getList('*', $where, 'inTurn DESC');
         $list = isset($data['list']) && !empty($data['list']) ? $data['list'] : [];
@@ -21,7 +26,11 @@ class GoodsCategoryService extends BaseService
             return $data;
         }
         $ids = array_column($list, 'gId');
-        $list = GoodsService::getAllByCondition(['id' => ['in', $ids]], null, '*');
+        $goodsWhere = ['id' => ['in', $ids]];
+        if (count($goodsCondition) > 0) {
+            $goodsWhere = array_merge($goodsWhere, $goodsCondition);
+        }
+        $list = GoodsService::getAllByCondition($goodsWhere, null, '*');
         $data['list'] = GoodsClass::groupGoodsBaseInfo($list, $ids);
         return $data;
     }

+ 7 - 0
biz-mall/message/classes/ChatClass.php

@@ -38,5 +38,12 @@ class ChatClass extends BaseClass
 		$respond = Yii::$app->redis->executeCommand('GET', [$key]);
 		return is_numeric($respond) ? $respond : 0;
 	}
+
+    // ----------------- 新建的 获取键的方法(参考上面的得来)----------------------
+    //最近联系人列表的键
+    public static function getLatestUsersKey($userId)
+    {
+        return "customer_chats:" . $userId;
+    }
 	
 }

+ 123 - 0
biz-mall/message/services/ChatService.php

@@ -2,11 +2,14 @@
 
 namespace bizMall\message\services;
 
+use bizHd\custom\classes\HdClass;
 use bizMall\base\services\BaseService;
 use bizMall\message\classes\ChatClass;
+use bizMall\shop\classes\ShopClass;
 use bizMall\user\services\UserService;
 use common\components\arrayUtil;
 use Yii;
+use yii\helpers\ArrayHelper;
 
 class ChatService extends BaseService
 {
@@ -153,4 +156,124 @@ class ChatService extends BaseService
 		return $data;
 	}
 
+	public static function getChatHistory($roomName)
+    {
+		if (empty($roomName)) {
+			return [];
+		}
+		try {
+			$list = Yii::$app->redis->executeCommand('LRANGE', [$roomName, 0, -1]);
+			if (empty($list)) {
+				return [];
+			}
+			$result = [];
+			foreach ($list as $item) {
+				$decoded = json_decode($item, true);
+				$struct = (json_last_error() === JSON_ERROR_NONE) ? $decoded : $item;
+				$content = $struct['content'];
+                $message = json_decode($content, true);
+				$result[] = json_decode($message['message'], true);
+			}
+			return $result;
+		} catch (\Throwable $e) {
+			Yii::error('getChatHistory redis error: ' . $e->getMessage(), __METHOD__);
+			return [];
+		}
+    }
+
+	// ------------------------------------------------  以下是新增的聊天方法  ------------------------------------------------
+
+    /**
+     * 最近聊天人(人:可能是客户,也可能是商家)
+     * @param int $userId
+     * @return array|\yii\db\ActiveRecord[]
+     */
+    public static function getLatestUsers($userId)
+    {
+        $cacheKey = ChatClass::getLatestUsersKey($userId);
+        //返回有序集合,从高分到低分排序
+        $return = Yii::$app->redis->executeCommand('ZREVRANGE', [$cacheKey, 0, -1, 'WITHSCORES']);
+        if (empty($return)) {
+            return [];
+        }
+        $i = 0;
+        $arr = [];
+        foreach ($return as $key => $val) {
+            if ($key % 2 == 0) {
+                $arr[$i]['shopId'] = $val;
+            } else {
+                $arr[$i]['time'] = $val;
+                $i++;
+            }
+        }
+        $userData = [];
+        //组合出最后聊天时间和未读消息数
+        foreach ($arr as $val) {
+            $shopId = $val['shopId'];
+            $float = floatval($val['time']);
+            $decimalPart = $float - floor($float);
+            $unReadNum = intval($decimalPart * 10000);
+            $time = intval($val['time']);
+            $date = date("Y-m-d H:i", $time);
+
+            $userData[$shopId] = ['time' => $date, 'unReadNum' => $unReadNum];
+        }
+        $ids = array_column($arr, 'shopId');
+        $where = [];
+        $where['userId'] = $userId;
+        $where['delStatus'] = 0;
+        $hdList = HdClass::getAllByCondition($where,'inTurn DESC, addTime DESC', 'customId, shopId');
+        // 生成以 shopId 为键的新数组
+        $hdListByShopId = ArrayHelper::index($hdList, 'shopId');
+        $shopList = ShopClass::getByIds($ids, null, null, 'id, avatar, shopName, merchantName');
+        foreach ($shopList as $shopId => $info) {
+            $shopList[$shopId]['unReadNum'] = isset($userData[$info['id']]['unReadNum']) ? $userData[$info['id']]['unReadNum'] : 0;
+            $shopList[$shopId]['chatTime'] = isset($userData[$info['id']]['time']) ? $userData[$info['id']]['time'] : 0;
+			$shopList[$shopId]['customId'] = isset($hdListByShopId[$info['id']]['customId']) ? $hdListByShopId[$info['id']]['customId'] : 0;
+        }
+        $shopList = arrayUtil::arraySort($shopList, 'chatTime', SORT_DESC);
+        return array_values($shopList);
+    }
+
+    /**
+     * @param int $userId 用户id
+     * @param string $unit 单位分:个数(person)消息(message)
+     * @return int
+     */
+    public static function getUnReadMsgCount($userId, $unit='person')
+    {
+        $cacheKey = ChatClass::getLatestUsersKey($userId);
+        //返回有序集合,从高分到低分排序
+        $return = Yii::$app->redis->executeCommand('ZREVRANGE', [$cacheKey, 0, -1, 'WITHSCORES']);
+        if (empty($return)) {
+            return 0;
+        }
+        $i = 0;
+        $arr = [];
+        foreach ($return as $key => $val) {
+            if ($key % 2 == 0) {
+                $arr[$i]['sId'] = $val;//shopId
+            } else {
+                $arr[$i]['score'] = $val;
+                $i++;
+            }
+        }
+
+        $msgCount = 0;
+        foreach ($arr as $val) {
+            $score = floatval($val['score']);
+            $decimalPart = $score - floor($score);
+            $unReadNum = intval($decimalPart * 10000 + 0.5); // 加0.5 -- 使用四舍五入来处理浮点数精度问题
+
+            //根据未读消息数的单位进行计算总数
+            if ($unit == 'person'){
+                $msgCount += ($unReadNum >= 1 ? 1 : 0);
+            } else if ($unit == 'message'){
+                $msgCount += $unReadNum;
+            }
+        }
+
+        return $msgCount;
+    }
+
 }

+ 2 - 1
biz-mall/user/classes/UserClass.php

@@ -2,7 +2,7 @@
 
 namespace bizMall\user\classes;
 
-use bizHd\custom\classes\CustomClass;
+use bizHd\custom\classes\HdClass;
 use bizMall\merchant\classes\MerchantAssetClass;
 use bizMall\merchant\classes\MerchantClass;
 use bizMall\user\services\UserIntegralService;
@@ -13,6 +13,7 @@ use common\components\wxUtil;
 use common\services\ImageService;
 use common\services\xhMerchantExtendService;
 use common\services\xhUserCapitalService;
+use common\services\xhUserMergeService;
 use Yii;
 use bizMall\base\classes\BaseClass;