Przeglądaj źródła

Merge branch 'master' of http://git.bocai108.com:10180/Ethan/Customer-Service

Jonlin 6 lat temu
rodzic
commit
f9fb320809

+ 2 - 2
application/admin/controller/Login.php

@@ -49,8 +49,8 @@ class Login extends Controller
                 return json(['code' => -5, 'data' => '', 'msg' => '您已被禁用']);
             }
 
-//            cookie('user_name',$userName);
-//            cookie('user_id',$userInfo['id']);
+            cookie('user_name',$userName);
+            cookie('user_id',$userInfo['id']);
 
             // 登陆成功 生成token
             $module = mt_rand(100000,999999);

+ 87 - 24
application/service/controller/History.php

@@ -40,13 +40,25 @@ class History extends Common
                 'browse',
                 'a.status',
                 'evaluate_id',
+                'servicelog_id',
             ];
             // 关联信息.
             $serviceLogJoin['groups b'] = 'a.group_id = b.id';
             $serviceLogWhere['kf_id']   = $getUserInfo->id;
+            // 分页.
+            $currentPage = input('get.currentPage', '1');
+            $pageSize    = input('get.pageSize', '10');
+            $offset      = (($currentPage - 1) * $pageSize);
             // 获取用户信息.
-            $serviceLog = model('ServiceLog')->selectServiceLog($serviceLogField, $serviceLogWhere, $serviceLogJoin);
-            $evaluate   = model('Evaluate')->getEvaluate();
+            $serviceLog      = model('ServiceLog')->selectServiceLog(
+                $serviceLogField,
+                $offset,
+                $pageSize,
+                $serviceLogWhere,
+                $serviceLogJoin
+            );
+            $countServiceLog = model('ServiceLog')->countServiceLog($serviceLogWhere);
+            $evaluate        = model('Evaluate')->getEvaluate();
             foreach ($serviceLog as $k => $v) {
                 foreach ($evaluate as $va) {
                     if ($v->evaluate_id === $va->evaluate_id) {
@@ -55,8 +67,13 @@ class History extends Common
                 }
             }
 
+            $result['total']       = $countServiceLog;
+            $result['countPage']   = (ceil(($result['total']) / $pageSize));
+            $result['currentPage'] = $currentPage;
+            $result['list']        = $serviceLog;
+            $result['pageSize']    = $pageSize;
 
-            return json(['code' => 200, 'data' => $serviceLog, 'msg' => '成功']);
+            return json(['code' => 200, 'data' => $result, 'msg' => '成功']);
         } catch (\Exception $e) {
             return json(['code' => $code, 'data' => [], 'msg' => $msg]);
         }//end try
@@ -82,35 +99,81 @@ class History extends Common
 
         try {
             // 获取用户信息.
-            $getUserToken = input('get.HTTP_userToken');
-            $getUserInfo     = $this->getUserInfo();
-            $serviceLogField = [
-                'user_id',
-                'user_name',
-                'user_avatar',
-                'user_ip',
-                'start_time',
-                'end_time',
-                'name',
-                'website',
-                'system',
-                'browse',
-                'a.status',
-                'evaluate_id',
-            ];
+            $servicelogId = input('get.servicelog_id');
+            $chatLogField = ['*'];
             // 关联信息.
-            $serviceLogJoin['groups b'] = 'a.group_id = b.id';
-            $serviceLogWhere['kf_id']   = $getUserInfo->id;
+            $chatLogWhere['servicelog_id'] = $servicelogId;
+            // 分页.
+            $currentPage = input('get.currentPage', '1');
+            $pageSize    = input('get.pageSize', '10');
+            $offset      = (($currentPage - 1) * $pageSize);
             // 获取用户信息.
-            $serviceLog = model('ServiceLog')->selectServiceLog($serviceLogField, $serviceLogWhere, $serviceLogJoin);
+            $chatLog      = model('ChatLog')->selectChatLog($chatLogField, $offset, $pageSize, $chatLogWhere);
+            $countChatLog = model('ChatLog')->countChatLog($chatLogWhere);
 
+            $result['total']       = $countChatLog;
+            $result['countPage']   = (ceil(($result['total']) / $pageSize));
+            $result['currentPage'] = $currentPage;
+            $result['list']        = $chatLog;
+            $result['pageSize']    = $pageSize;
 
-            return json(['code' => 200, 'data' => $serviceLog, 'msg' => '成功']);
+            return json(['code' => 200, 'data' => $result, 'msg' => '成功']);
         } catch (\Exception $e) {
             return json(['code' => $code, 'data' => [], 'msg' => $msg]);
         }//end try
 
-    }//end historyList()
+    }//end historyInfo()
+
+
+    /**
+     * 获取用户会话历史详细
+     *
+     * @access public
+     * @return array JsonString
+     */
+    public function userHistory()
+    {
+        // 验证token.
+        $tokenStatus = $this->verifyToken();
+        $code        = -2;
+        $msg         = '错误';
+        if ($tokenStatus === false) {
+            return json(['code' => $code, 'data' => [], 'msg' => $msg]);
+        }
+
+        try {
+            // 获取用户ID.
+            $accountId    = input('get.account_id');
+            $chatLogField = ['*'];
+            // 关联信息.
+            $chatLogWhere['from_id'] = $accountId;
+            $chatLogWhereOr['to_id'] = $accountId;
+            // 分页.
+            $currentPage = input('get.currentPage', '1');
+            $pageSize    = input('get.pageSize', '10');
+            $offset      = (($currentPage - 1) * $pageSize);
+            // 获取用户信息.
+            $chatLog      = model('ChatLog')->userChatLog(
+                $chatLogField,
+                $chatLogWhere,
+                $chatLogWhereOr,
+                $offset,
+                $pageSize
+            );
+            $countChatLog = model('ChatLog')->userChatLogCount($chatLogWhere, $chatLogWhereOr);
+
+            $result['total']       = $countChatLog;
+            $result['countPage']   = (ceil(($result['total']) / $pageSize));
+            $result['currentPage'] = $currentPage;
+            $result['list']        = $chatLog;
+            $result['pageSize']    = $pageSize;
+
+            return json(['code' => 200, 'data' => $result, 'msg' => '成功']);
+        } catch (\Exception $e) {
+            return json(['code' => $code, 'data' => [], 'msg' => $msg]);
+        }//end try
+
+    }//end userHistory()
 
 
 }

+ 4 - 1
application/service/controller/Index.php

@@ -69,6 +69,7 @@ class Index extends Common
             $wordsField               = [
                 'id',
                 'content',
+                'title',
             ];
             $sysWordsWhere['status']  = 1;
             $sysWordsWhere['user_id'] = 0;
@@ -93,8 +94,10 @@ class Index extends Common
 
     public function index()
     {
+        $getUserInfo = $this->getUserInfo();
+
         // 客服信息
-        $userInfo = db('users')->where('id', cookie('l_user_id'))->find();
+        $userInfo = db('users')->where('id', 1)->find();
 
         $this->assign([
             'uinfo' => $userInfo,

+ 153 - 0
application/service/controller/Words.php

@@ -0,0 +1,153 @@
+<?php
+namespace app\service\controller;
+
+/**
+ * 个人快捷语类
+ */
+class Words extends Common
+{
+
+
+    /**
+     * 获取用户快捷语
+     *
+     * @access public
+     * @return array JsonString
+     */
+    public function userWords()
+    {
+        // 验证token.
+        $tokenStatus = $this->verifyToken();
+        $code        = -2;
+        $msg         = '错误';
+        if ($tokenStatus === false) {
+            return json(['code' => $code, 'data' => [], 'msg' => $msg]);
+        }
+
+        try {
+            // 获取用户信息.
+            $getUserInfo = $this->getUserInfo();
+            // 获取字段.
+            $wordsField = [
+                'id',
+                'content',
+                'title',
+            ];
+            // 条件.
+            $userWordsWhere['user_id'] = $getUserInfo->id;
+            // 查询用户私有快捷语.
+            $userWords = model('words')->selectWords($wordsField, $userWordsWhere);
+
+            return json(['code' => 200, 'data' => $userWords, 'msg' => '成功']);
+        } catch (\Exception $e) {
+            return json(['code' => $code, 'data' => [], 'msg' => $msg]);
+        }//end try
+
+    }//end userWords()
+
+
+    /**
+     * 快捷语修改
+     *
+     * @access public
+     * @return array JsonString
+     */
+    public function updateWords()
+    {
+        // 验证token.
+        $tokenStatus = $this->verifyToken();
+        $code        = -2;
+        $msg         = '错误';
+        if ($tokenStatus === false) {
+            return json(['code' => $code, 'data' => [], 'msg' => $msg]);
+        }
+
+        try {
+            // 获取用户信息.
+            $getUserInfo    = $this->getUserInfo();
+            $userWordsWhere = [
+                'user_id' => $getUserInfo->id,
+                'id'      => input('post.id'),
+            ];
+            $content        = input('post.content');
+            $status         = input('post.status');
+            $title          = input('post.title');
+            // 更新内容.
+            if (empty($content) === false) {
+                $userWordsData['content'] = input('post.content');
+            }
+
+            if (empty($status) === false) {
+                $userWordsData['status'] = input('post.status');
+            }
+
+            if (empty($title) === false) {
+                $userWordsData['title'] = input('post.title');
+            }
+
+            // 更新.
+            if (isset($userWordsData) === true) {
+                $updateWordsResult = model('Words')->updateWords($userWordsWhere, $userWordsData);
+                if (empty($updateWordsResult) === false) {
+                    $result = true;
+                }
+            }
+
+            // 参数返回.
+            if (isset($result) === true) {
+                return json(['code' => 200, 'data' => [], 'msg' => '成功']);
+            } else {
+                return json(['code' => 1, 'data' => [], 'msg' => 1]);
+            }
+        } catch (\Exception $e) {
+            return json(['code' => $code, 'data' => [], 'msg' => $msg]);
+        }//end try
+
+    }//end updateWords()
+
+
+    /**
+     * 获取会话历史详细
+     *
+     * @access public
+     * @return array JsonString
+     */
+    public function historyInfo()
+    {
+        // 验证token.
+        $tokenStatus = $this->verifyToken();
+        $code        = -2;
+        $msg         = '错误';
+        if ($tokenStatus === false) {
+            return json(['code' => $code, 'data' => [], 'msg' => $msg]);
+        }
+
+        try {
+            // 获取用户信息.
+            $servicelogId = input('get.servicelog_id');
+            $chatLogField = ['*'];
+            // 关联信息.
+            $chatLogWhere['servicelog_id'] = $servicelogId;
+            // 分页.
+            $currentPage = input('get.currentPage', '1');
+            $pageSize    = input('get.pageSize', '10');
+            $offset      = (($currentPage - 1) * $pageSize);
+            // 获取用户信息.
+            $chatLog      = model('ChatLog')->selectChatLog($chatLogField, $offset, $pageSize, $chatLogWhere);
+            $countChatLog = model('ChatLog')->countChatLog($chatLogWhere);
+
+            $result['total']       = $countChatLog;
+            $result['countPage']   = (ceil(($result['total']) / $pageSize));
+            $result['currentPage'] = $currentPage;
+            $result['list']        = $chatLog;
+            $result['pageSize']    = $pageSize;
+
+            return json(['code' => 200, 'data' => $result, 'msg' => '成功']);
+        } catch (\Exception $e) {
+            return json(['code' => $code, 'data' => [], 'msg' => $msg]);
+        }//end try
+
+    }//end historyInfo()
+
+
+}

+ 99 - 0
application/service/model/ChatLog.php

@@ -0,0 +1,99 @@
+<?php
+namespace app\service\model;
+
+use think\Model;
+
+/**
+ * 会话记录模型
+ */
+class ChatLog extends Model
+{
+
+
+    /**
+     * 数据筛选
+     *
+     * @access public
+     * @param  mixed $field  字段.
+     * @param  mixed $offset 分页开始.
+     * @param  mixed $limit  分页大小.
+     * @param  mixed $where   条件.
+     * @return array 返回类型
+     */
+    public function selectChatLog($field, $offset, $limit, $where=[])
+    {
+        $result = $this->field($field);
+
+        if (empty($where) === false) {
+            $result = $result->where($where);
+        }
+
+        $result = $result->limit($offset, $limit)->order('time_line', 'desc')->select();
+        return $result;
+
+    }//end selectChatLog()
+
+
+    /**
+     * 数据总数
+     *
+     * @access public
+     * @param mixed $where 条件
+     * @return array 返回类型
+     */
+    public function countChatLog($where=[])
+    {
+        $result = $this;
+
+        if (empty($where) === false) {
+            $result = $result->where($where);
+        }
+
+        $result = $result->count();
+        return $result;
+
+    }//end countChatLog()
+
+
+    /**
+     * 用户数据筛选
+     *
+     * @access public
+     * @param mixed $field 字段
+     * @param mixed $offset 分页开始
+     * @param mixed $limit 分页大小
+     * @param mixed $where 条件
+     * @param mixed $whereOr 条件
+     * @return array 返回类型
+     */
+    public function userChatLog($field, $where, $whereOr, $offset, $limit)
+    {
+        $result = $this
+            ->field($field)
+            ->where($where)
+            ->whereOr($whereOr)
+            ->limit($offset, $limit)
+            ->order('time_line', 'desc')
+            ->select();
+        return $result;
+
+    }//end userChatLog()
+
+
+    /**
+     * 用户数据总数
+     *
+     * @access public
+     * @param  mixed $where   条件.
+     * @param  mixed $whereOr 条件.
+     * @return array 返回类型
+     */
+    public function userChatLogCount($where, $whereOr)
+    {
+        $result = $this->where($where)->whereOr($whereOr)->count();
+        return $result;
+
+    }//end userChatLogCount()
+
+
+}

+ 25 - 2
application/service/model/ServiceLog.php

@@ -17,9 +17,11 @@ class ServiceLog extends Model
      * @param mixed $field 字段
      * @param mixed $where 条件
      * @param mixed $join 关联
+     * @param mixed $offset 分页开始
+     * @param mixed $limit 分页大小
      * @return array 返回类型
      */
-    public function selectServiceLog($field, $where=[], $join=[])
+    public function selectServiceLog($field, $offset, $limit, $where=[], $join=[])
     {
         $result = $this->field($field);
         if (empty($join) === false) {
@@ -33,10 +35,31 @@ class ServiceLog extends Model
             $result = $result->where($where);
         }
 
-        $result = $result->select();
+        $result = $result->limit($offset, $limit)->order('start_time', 'desc')->select();
         return $result;
 
     }//end selectServiceLog()
 
 
+    /**
+     * 数据总数
+     *
+     * @access public
+     * @param mixed $where 条件
+     * @return array 返回类型
+     */
+    public function countServiceLog($where=[])
+    {
+        $result = $this;
+
+        if (empty($where) === false) {
+            $result = $result->where($where);
+        }
+
+        $result = $result->count();
+        return $result;
+
+    }//end countServiceLog()
+
+
 }

+ 17 - 0
application/service/model/Words.php

@@ -31,4 +31,21 @@ class Words extends Model
     }//end selectWords()
 
 
+    /**
+     * 数据修改
+     *
+     * @access public
+     * @param mixed $data 数据
+     * @param mixed $where 条件
+     * @return array 返回类型
+     */
+    public function updateWords($where, $data)
+    {
+        $result = $this->where($where)->update($data);
+
+        return $result;
+
+    }//end updateWords()
+
+
 }

+ 4 - 3
public/static/customer/js/whisper-cli.js

@@ -25,9 +25,9 @@ if(config != undefined && config.socket != undefined){
     socket.onopen = function(res) {
         console.log('握手成功');
         // 登录
-        var login_data = '{"type":"userInit", "uid": 1, "name" : "' + config.name +
+        var login_data = '{"type":"userInit", "uid": "' + config.uid + '", "name" : "' + config.name +
             '", "avatar" : "' + config.avatar + '", "group" : ' + config.group + '}';
-        //socket.send(login_data);
+        socket.send(login_data);
 
         // 解锁
         unlockTextarea();
@@ -219,7 +219,8 @@ function sendMsg(sendMsg){
     // 发送消息
     socket.send(JSON.stringify({
         type: 'chatMessage',
-        data: {to_id: kf_id, content: msg, from_id: config.uid}
+        data: {to_id: kf_id, to_name: kf_name, content: msg, from_name: config.name,
+            from_id: config.uid, from_avatar: config.avatar, conversationId: 1}
     }));
 
     // 储存我发出的信息

+ 1 - 1
public/static/service/js/whisper.js

@@ -291,7 +291,7 @@ function sendMessage(sendMsg) {
     socket.send(JSON.stringify({
         type: 'chatMessage',
         data: {to_id: uid, to_name: uname, content: msg, from_name: uinfo.username,
-            from_id: uinfo.id, from_avatar: uinfo.avatar}
+            from_id: uinfo.id, from_avatar: uinfo.avatar, conversationId: 1}
     }));
 
     $("#u-" + uid).append(word);

+ 146 - 119
vendor/GatewayWorker_windows/Applications/whisper/Events.php

@@ -17,6 +17,7 @@
  * 如果发现业务卡死,可以将下面declare打开(去掉//注释),并执行php start.php reload
  * 然后观察一段时间workerman.log看是否有process_timeout异常
  */
+
 //declare(ticks=1);
 use \GatewayWorker\Lib\Gateway;
 use Workerman\Lib\Timer;
@@ -46,20 +47,20 @@ class Events
         if (empty(self::$global)) {
             self::$global = new \GlobalData\Client('127.0.0.1:2207');
             // 客服列表
-            if(is_null(self::$global->kfList)){
+            if (is_null(self::$global->kfList)) {
                 self::$global->kfList = [];
             }
             // 会员列表[动态的,这里面只是目前未被分配的会员信息]
-            if(is_null(self::$global->userList)){
+            if (is_null(self::$global->userList)) {
                 self::$global->userList = [];
             }
             // 会员以 uid 为key的信息简表,只有在用户退出的时候,才去执行修改
-            if(is_null(self::$global->uidSimpleList)){
+            if (is_null(self::$global->uidSimpleList)) {
                 self::$global->uidSimpleList = [];
             }
             // 当天的累积接入值
             $key = date('Ymd') . 'total_in';
-            if(is_null(self::$global->$key)){
+            if (is_null(self::$global->$key)) {
                 self::$global->$key = 0;
 
                 $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
@@ -68,7 +69,7 @@ class Events
             }
             // 成功接入值
             $key = date('Ymd') . 'success_in';
-            if(is_null(self::$global->$key)){
+            if (is_null(self::$global->$key)) {
                 self::$global->$key = 0;
 
                 $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
@@ -78,13 +79,13 @@ class Events
         }
 
         // 定时统计数据
-        if(0 === $worker->id){
+        if (0 === $worker->id) {
             // 1分钟统计一次实时数据
-            Timer::add(60 * 1, function(){
+            Timer::add(60 * 1, function () {
                 self::writeLog(1);
             });
             // 40分钟写一次当前日期点数的log数据
-            Timer::add(60 * 40, function(){
+            Timer::add(60 * 40, function () {
                 self::writeLog(2);
             });
         }
@@ -100,7 +101,7 @@ class Events
     {
         // 检测是否开启自动应答
         $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 1');
-        if(!empty($sayHello) && 1 == $sayHello['0']['status']){
+        if (!empty($sayHello) && 1 == $sayHello['0']['status']) {
 
             $hello = [
                 'message_type' => 'helloMessage',
@@ -123,20 +124,23 @@ class Events
      */
     public static function onMessage($client_id, $message)
     {
-        if ($message!='{"type":"ping"}'){
-            echo "onMessage: ".$message."\r\n";
-           // print_r([self::$global->kfList,self::$global->userList,  self::$global->uidSimpleList]);
+        if ($message == '{"type":"ping"}') {
+            Gateway::sendToCurrentClient('{"type":"pong"}');
+            return;
+        } else {
+            echo "onMessage: " . $message . "\r\n";
+            //print_r([self::$global->kfList, self::$global->userList, self::$global->uidSimpleList, self::$global->userToKf]);
         }
 
         $message = json_decode($message, true);
         switch ($message['type']) {
             // 客服初始化
             case 'init':
-               $kfList = self::$global->kfList;
+                $kfList = self::$global->kfList;
                 // 如果该客服未在内存中记录则记录
-                if(!isset($kfList[$message['group']]) || !array_key_exists($message['uid'], $kfList[$message['group']])){
+                if (!isset($kfList[$message['group']]) || !array_key_exists($message['uid'], $kfList[$message['group']])) {
 
-                    do{
+                    do {
                         $newKfList = $kfList;
                         $newKfList[$message['group']][$message['uid']] = [
                             'id' => $message['uid'],
@@ -146,14 +150,14 @@ class Events
                             'task' => 0,
                             'user_info' => []
                         ];
-                    }while(!self::$global->cas('kfList', $kfList, $newKfList));
+                    } while (!self::$global->cas('kfList', $kfList, $newKfList));
                     unset($newKfList, $kfList);
-                }else if(isset($kfList[$message['group']][$message['uid']])){
+                } else if (isset($kfList[$message['group']][$message['uid']])) {
 
-                    do{
+                    do {
                         $newKfList = $kfList;
                         $newKfList[$message['group']][$message['uid']]['client_id'] = $client_id;
-                    }while(!self::$global->cas('kfList', $kfList, $newKfList));
+                    } while (!self::$global->cas('kfList', $kfList, $newKfList));
                     unset($newKfList, $kfList);
                 }
 
@@ -166,8 +170,8 @@ class Events
             case 'userInit';
                 $userList = self::$global->userList;
                 // 如果该顾客未在内存中记录则记录
-                if(!array_key_exists($message['uid'], $userList)){
-                    do{
+                if (!array_key_exists($message['uid'], $userList)) {
+                    do {
                         $NewUserList = $userList;
                         $NewUserList[$message['uid']] = [
                             'id' => $message['uid'],
@@ -181,27 +185,27 @@ class Events
                             'client_id' => $client_id
                         ];
 
-                    }while(!self::$global->cas('userList', $userList, $NewUserList));
+                    } while (!self::$global->cas('userList', $userList, $NewUserList));
                     unset($NewUserList, $userList);
 
                     // 维护 UID对应的client_id 数组
-                    do{
+                    do {
                         $old = $newList = self::$global->uidSimpleList;
                         $newList[$message['uid']] = [
                             $client_id,
                             $message['group']
                         ];
 
-                    }while(!self::$global->cas('uidSimpleList', $old, $newList));
+                    } while (!self::$global->cas('uidSimpleList', $old, $newList));
                     unset($old, $newList);
 
                     // 写入接入值
                     $key = date('Ymd') . 'total_in';
                     self::$global->$key = 0;
-                    do{
+                    do {
                         $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
                         unset(self::$global->$oldKey);
-                    }while(!self::$global->increment($key));
+                    } while (!self::$global->increment($key));
                     unset($key);
                 }
 
@@ -213,9 +217,8 @@ class Events
                 break;
             // 聊天
             case 'chatMessage':
-
                 $client = Gateway::getClientIdByUid($message['data']['to_id']);
-                if(!empty($client)){
+                if (!empty($client)) {
                     $chat_message = [
                         'message_type' => 'chatMessage',
                         'data' => [
@@ -237,6 +240,7 @@ class Events
                         'to_id' => $message['data']['to_id'],
                         'to_name' => $message['data']['to_name'],
                         'content' => $message['data']['content'],
+                        'servicelog_id' => $message['data']['conversationId'],
                         'time_line' => time()
                     ];
 
@@ -249,8 +253,8 @@ class Events
                 // 通知客户端转接中
                 $simpleList = self::$global->uidSimpleList;
 
-                if(!isset($simpleList[$message['uid']])){ // 客户已经退出
-                    return ;
+                if (!isset($simpleList[$message['uid']])) { // 客户已经退出
+                    return;
                 }
 
                 $userClient = $simpleList[$message['uid']]['0'];
@@ -267,10 +271,10 @@ class Events
 
                 // 从当前客服的服务表中删除这个会员
                 $old = $kfList = self::$global->kfList;
-                if(!isset($kfList[$userGroup])){
+                if (!isset($kfList[$userGroup])) {
                     $waitMsg = '暂时没有相关客服上班,请稍后再咨询。';
                     // 逐一通知
-                    foreach(self::$global->userList as $vo){
+                    foreach (self::$global->userList as $vo) {
 
                         $waitMessage = [
                             'message_type' => 'wait',
@@ -281,16 +285,16 @@ class Events
                         Gateway::sendToClient($userClient, json_encode($waitMessage));
                         unset($waitMessage);
                     }
-                    return ;
+                    return;
                 }
                 $myList = $kfList[$userGroup]; // 该客服分组数组
-                foreach($myList as $key=>$vo){
-                    if(in_array($userClient, $vo['user_info'])){
+                foreach ($myList as $key => $vo) {
+                    if (in_array($userClient, $vo['user_info'])) {
 
                         // 维护现在的该客服的服务信息
                         $kfList[$userGroup][$key]['task'] -= 1; // 当前服务的人数 -1
-                        foreach($vo['user_info'] as $k=>$v){
-                            if($userClient == $v){
+                        foreach ($vo['user_info'] as $k => $v) {
+                            if ($userClient == $v) {
                                 unset($kfList[$userGroup][$key]['user_info'][$k]);
                                 break;
                             }
@@ -299,12 +303,13 @@ class Events
                         break;
                     }
                 }
-                while(!self::$global->cas('kfList', $old, $kfList)){}; // 刷新内存中客服的服务列表
+                while (!self::$global->cas('kfList', $old, $kfList)) {
+                }; // 刷新内存中客服的服务列表
                 unset($old, $kfList, $myList);
 
                 // 将会员加入队列中
                 $userList = self::$global->userList;
-                do{
+                do {
                     $NewUserList = $userList;
                     $NewUserList[$message['uid']] = [
                         'id' => $message['uid'],
@@ -315,7 +320,7 @@ class Events
                         'client_id' => $userClient
                     ];
 
-                }while(!self::$global->cas('userList', $userList, $NewUserList));
+                } while (!self::$global->cas('userList', $userList, $NewUserList));
                 unset($NewUserList, $userList);
 
                 // 执行会员分配通知双方
@@ -323,10 +328,10 @@ class Events
                 unset($userClient, $userGroup);
 
                 break;
-			case 'closeUser':
+            case 'closeUser':
 
                 $userInfo = self::$global->uidSimpleList;
-                if(isset($userInfo[$message['uid']])){
+                if (isset($userInfo[$message['uid']])) {
                     $waitMessage = [
                         'message_type' => 'wait',
                         'data' => [
@@ -349,7 +354,7 @@ class Events
             // 客服关闭会话.
             case 'kfCloseUser':
                 $client = Gateway::getClientIdByUid($message['data']['to_id']);
-                if(!empty($client)){
+                if (!empty($client)) {
                     self::serverClose($client['0']);
                 }
                 break;
@@ -413,9 +418,9 @@ class Events
         $isServiceUserOut = false;
         // 将会员服务信息,从客服的服务列表中移除
         $old = $kfList = self::$global->kfList;
-        foreach($kfList as $k=>$v){
-            foreach($v as $key=>$vo){
-                if(in_array($client_id, $vo['user_info'])){
+        foreach ($kfList as $k => $v) {
+            foreach ($v as $key => $vo) {
+                if (in_array($client_id, $vo['user_info'])) {
 
                     $isServiceUserOut = true;
 
@@ -425,8 +430,8 @@ class Events
                     // 从会员的内存表中检索出该会员的信息,并更新内存
                     $oldSimple = $simpleList = self::$global->uidSimpleList;
                     $outUser = [];
-                    foreach($simpleList as $u=>$c){
-                        if($c['0'] == $client_id){
+                    foreach ($simpleList as $u => $c) {
+                        if ($c['0'] == $client_id) {
                             $outUser[] = [
                                 'user_id' => $u,
                                 'group_id' => $c['1']
@@ -435,12 +440,13 @@ class Events
                             break;
                         }
                     }
-                    while(!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)){};
+                    while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
+                    };
                     unset($oldSimple, $simpleList);
 
                     $outUser = self::$db->query("select `user_id`,`group_id` from `ws_service_log` where `client_id`= '" . $client_id . "'");
                     // 通知 客服删除退出的用户
-                    if(!empty($outUser)){
+                    if (!empty($outUser)) {
                         $del_message = [
                             'message_type' => 'delUser',
                             'data' => [
@@ -457,30 +463,31 @@ class Events
 
                     // 维护现在的该客服的服务信息
                     $kfList[$k][$key]['task'] -= 1; // 当前服务的人数 -1
-                    foreach($vo['user_info'] as $m=>$l){
-                        if($client_id == $l){
+                    foreach ($vo['user_info'] as $m => $l) {
+                        if ($client_id == $l) {
                             unset($kfList[$k][$key]['user_info'][$m]);
                             break;
                         }
                     }
 
                     // 刷新内存中客服的服务列表
-                    while(!self::$global->cas('kfList', $old, $kfList)){};
+                    while (!self::$global->cas('kfList', $old, $kfList)) {
+                    };
                     unset($old, $kfList);
 
                     break;
                 }
             }
 
-            if($isServiceUserOut) break;
+            if ($isServiceUserOut) break;
         }
 
 
         // 尝试从排队的用户中删除退出的客户端
-        if(false == $isServiceUserOut){
+        if (false == $isServiceUserOut) {
             $old = $userList = self::$global->userList;
-            foreach(self::$global->userList as $key=>$vo){
-                if($client_id == $vo['client_id']){
+            foreach (self::$global->userList as $key => $vo) {
+                if ($client_id == $vo['client_id']) {
 
                     $isServiceUserOut = true;
 
@@ -488,34 +495,37 @@ class Events
                     break;
                 }
             }
-            while(!self::$global->cas('userList', $old, $userList)){};
+            while (!self::$global->cas('userList', $old, $userList)) {
+            };
 
             // 从会员的内存表中检索出该会员的信息,并更新内存
             $oldSimple = $simpleList = self::$global->uidSimpleList;
-            foreach($simpleList as $u=>$c){
-                if($c['0'] == $client_id){
+            foreach ($simpleList as $u => $c) {
+                if ($c['0'] == $client_id) {
                     unset($simpleList[$u]);
                     break;
                 }
             }
-            while(!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)){};
+            while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
+            };
             unset($oldSimple, $simpleList);
         }
 
         // 尝试是否是客服退出
-        if(false == $isServiceUserOut){
+        if (false == $isServiceUserOut) {
             $old = $kfList = self::$global->kfList;
-            foreach(self::$global->kfList as $k=>$v){
-                foreach($v as $key=>$vo){
+            foreach (self::$global->kfList as $k => $v) {
+                foreach ($v as $key => $vo) {
                     // 客服服务列表中无数据,才去删除客服内存信息
-                    if($client_id == $vo['client_id'] && (0 == count($vo['user_info']))){
+                    if ($client_id == $vo['client_id'] && (0 == count($vo['user_info']))) {
                         unset($kfList[$k][$key]);
                         break;
                     }
                 }
             }
 
-            while(!self::$global->cas('kfList', $old, $kfList)){};
+            while (!self::$global->cas('kfList', $old, $kfList)) {
+            };
         }
     }
 
@@ -532,10 +542,12 @@ class Events
         $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
         unset($maxNumber);
 
-        if(1 == $res['code']){
+        if (1 == $res['code']) {
 
-            while(!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])){}; // 更新客服数据
-            while(!self::$global->cas('userList', self::$global->userList, $res['data']['5'])){}; // 更新会员数据
+            while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
+            }; // 更新客服数据
+            while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
+            }; // 更新会员数据
 
             // 通知会员发送信息绑定客服的id
             $noticeUser = [
@@ -560,7 +572,7 @@ class Events
 
             // 逐一通知
             $number = 1;
-            foreach(self::$global->userList as $vo){
+            foreach (self::$global->userList as $vo) {
 
                 $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
                 $waitMessage = [
@@ -578,20 +590,20 @@ class Events
             // 写入接入值
             $key = date('Ymd') . 'success_in';
             self::$global->$key = 0;
-            do{
+            do {
                 $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
                 unset(self::$global->$oldKey);
-            }while(!self::$global->increment($key));
+            } while (!self::$global->increment($key));
             unset($key);
 
-        }else{
+        } else {
 
-            switch ($res['code']){
+            switch ($res['code']) {
 
                 case -1:
                     $waitMsg = '暂时没有客服上班,请稍后再咨询。';
                     // 逐一通知
-                    foreach(self::$global->userList as $vo){
+                    foreach (self::$global->userList as $vo) {
 
                         $waitMessage = [
                             'message_type' => 'wait',
@@ -609,7 +621,7 @@ class Events
                 case -4:
                     // 逐一通知
                     $number = 1;
-                    foreach(self::$global->userList as $vo){
+                    foreach (self::$global->userList as $vo) {
 
                         $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
                         $waitMessage = [
@@ -641,36 +653,18 @@ class Events
         $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
         unset($maxNumber);
 
-        if(1 == $res['code']){
+        if (1 == $res['code']) {
 
-            while(!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])){}; // 更新客服数据
-            while(!self::$global->cas('userList', self::$global->userList, $res['data']['5'])){}; // 更新会员数据
+            while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
+            }; // 更新客服数据
+            while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
+            }; // 更新会员数据
             $userToKf = self::$global->userToKf;
             $userToKf[$res['data']['3']['id']] = [
                 $res['data']['3']['id'],
                 $res['data']['0']
             ];
             self::$global->userToKf = $userToKf;
-            // 通知会员发送信息绑定客服的id
-            $noticeUser = [
-                'message_type' => 'connect',
-                'data' => [
-                    'kf_id' => $res['data']['0'],
-                    'kf_name' => $res['data']['1']
-                ]
-            ];
-            Gateway::sendToClient($client_id, json_encode($noticeUser));
-            unset($noticeUser);
-
-            // 通知客服端绑定会员的信息
-            $noticeKf = [
-                'message_type' => 'connect',
-                'data' => [
-                    'user_info' => $res['data']['3']
-                ]
-            ];
-            Gateway::sendToClient($res['data']['2'], json_encode($noticeKf));
-            unset($noticeKf);
 
             // 服务信息入库
             $serviceLog = [
@@ -689,22 +683,46 @@ class Events
                 'end_time' => 0
             ];
 
-            self::$db->insert('ws_service_log')->cols($serviceLog)->query();
+            $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
             unset($serviceLog);
 
+
+            // 通知会员发送信息绑定客服的id
+            $noticeUser = [
+                'message_type' => 'connect',
+                'data' => [
+                    'kf_id' => $res['data']['0'],
+                    'conversationId' => $conversationId,
+                    'kf_name' => $res['data']['1']
+                ]
+            ];
+            Gateway::sendToClient($client_id, json_encode($noticeUser));
+            unset($noticeUser);
+
+            // 通知客服端绑定会员的信息
+            $noticeKf = [
+                'message_type' => 'connect',
+                'data' => [
+                    'user_info' => $res['data']['3'],
+                    'conversationId' => $conversationId,
+                ]
+            ];
+            Gateway::sendToClient($res['data']['2'], json_encode($noticeKf));
+            unset($noticeKf);
+
             // 写入接入值
             $key = date('Ymd') . 'success_in';
             self::$global->$key = 0;
-            do{
+            do {
                 $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
                 unset(self::$global->$oldKey);
-            }while(!self::$global->increment($key));
+            } while (!self::$global->increment($key));
             unset($key);
 
-        }else{
+        } else {
 
             $waitMsg = '';
-            switch ($res['code']){
+            switch ($res['code']) {
 
                 case -1:
                     $waitMsg = '暂时没有客服上班,请稍后再咨询。';
@@ -742,22 +760,22 @@ class Events
     private static function assignmentTask($kfList, $userList, $group, $total)
     {
         // 没有客服上线
-        if(empty($kfList) || empty($kfList[$group])){
+        if (empty($kfList) || empty($kfList[$group])) {
             return ['code' => -1];
         }
 
         // 没有待分配的会员
-        if(empty($userList)){
+        if (empty($userList)) {
             return ['code' => -2];
         }
 
         // 未设置每个客服可以服务多少人
-        if(0 == $total){
+        if (0 == $total) {
             return ['code' => -3];
         }
 
         // 查看该组的客服是否在线
-        if(!isset($kfList[$group])){
+        if (!isset($kfList[$group])) {
             return ['code' => -1];
         }
 
@@ -768,8 +786,8 @@ class Events
         $min = $kf['task'];
         $flag = $kf['id'];
 
-        foreach($kfList[$group] as $key=>$vo){
-            if($vo['task'] < $min){
+        foreach ($kfList[$group] as $key => $vo) {
+            if ($vo['task'] < $min) {
                 $min = $vo['task'];
                 $flag = $key;
             }
@@ -777,7 +795,7 @@ class Events
         unset($kf);
 
         // 需要排队了
-        if($kfList[$group][$flag]['task'] == $total){
+        if ($kfList[$group][$flag]['task'] == $total) {
             return ['code' => -4];
         }
 
@@ -804,9 +822,9 @@ class Events
     private static function getMaxServiceNum()
     {
         $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
-        if(!empty($maxNumber)){
+        if (!empty($maxNumber)) {
             $maxNumber = 5;
-        }else{
+        } else {
             $maxNumber = $maxNumber['0']['max_service'];
         }
 
@@ -820,8 +838,8 @@ class Events
     private static function writeLog($flag = 1)
     {
         // 上午 8点 到 22 点开始统计
-        if(date('H') < 8 || date('H') > 22){
-            return ;
+        if (date('H') < 8 || date('H') > 22) {
+            return;
         }
 
         // 当前正在接入的人 和 在线客服数
@@ -829,12 +847,12 @@ class Events
 
         $nowTalking = 0;
         $onlineKf = 0;
-        if(!empty($kfList)){
+        if (!empty($kfList)) {
 
-            foreach($kfList as $key=>$vo){
+            foreach ($kfList as $key => $vo) {
 
                 $onlineKf += count($vo);
-                foreach($vo as $k=>$v){
+                foreach ($vo as $k => $v) {
                     $nowTalking += count($v['user_info']);
                 }
             }
@@ -855,7 +873,7 @@ class Events
         ];
         self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
 
-        if(2 == $flag){
+        if (2 == $flag) {
             $param = [
                 'is_talking' => $nowTalking,
                 'in_queue' => $inQueue,
@@ -923,4 +941,13 @@ class Events
         }
         Gateway::sendToClient($client_id, json_encode($chat_message));
     }
+
+
+    //踢掉同一用户的旧用户
+    private static function tickOlduser($uid)
+    {
+
+    }
+
+
 }

+ 16 - 10
vendor/GatewayWorker_windows/Applications/whisper/start_gateway.php

@@ -11,6 +11,7 @@
  * @link http://www.workerman.net/
  * @license http://www.opensource.org/licenses/mit-license.php MIT License
  */
+
 use \Workerman\Worker;
 use \Workerman\WebServer;
 use \GatewayWorker\Gateway;
@@ -37,21 +38,27 @@ $gateway->registerAddress = '127.0.0.1:1238';
 // 心跳间隔
 $gateway->pingInterval = 10;
 // 心跳数据
-$gateway->pingData = '{"message_type":"ping"}';
+$gateway->pingData = '{"type":"ping"}';
+
 
 // 当客户端连接上来时,设置连接的onWebSocketConnect,即在websocket握手时的回调
-$gateway->onConnect = function($connection)
-{
-    $connection->onWebSocketConnect = function($connection , $http_header)
-    {
-        $apiToken = md5('Customer-Service'.strtotime(date('Y-m-d')).$_SERVER['HTTP_ORIGIN']);
+$gateway->onConnect = function ($connection) {
+    $connection->onWebSocketConnect = function ($connection, $http_header) {
+        $apiToken = md5('Customer-Service' . strtotime(date('Y-m-d')) . $_SERVER['HTTP_ORIGIN']);
         //echo $apiToken."/".$_GET['apiToken'];
         $_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
         $_SESSION['origin'] = $_SERVER['HTTP_ORIGIN'];
+        $getToken = isset($_GET['apiToken']) ? $_GET['apiToken'] : '';
 
-        if ($_GET['apiToken'] !== $apiToken) {
-            $connection->close();
+        if ($getToken !== $apiToken) {
+             //$connection->close();
+            // return;
         }
+        $_SESSION['remotip'] = $connection->getRemoteIp();
+        $_SESSION['remotport'] = $connection->getRemotePort();
+        $_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
+        $_SESSION['origin'] = $_SERVER['HTTP_ORIGIN'];
+
         // 可以在这里判断连接来源是否合法,不合法就关掉连接
         // $_SERVER['HTTP_ORIGIN']标识来自哪个站点的页面发起的websocket链接
         /*if($_SERVER['HTTP_ORIGIN'] != 'http://kedou.workerman.net')
@@ -64,8 +71,7 @@ $gateway->onConnect = function($connection)
 };
 
 // 如果不是在根目录启动,则运行runAll方法
-if(!defined('GLOBAL_START'))
-{
+if (!defined('GLOBAL_START')) {
     Worker::runAll();
 }