Events.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. /**
  15. * 用于检测业务代码死循环或者长时间阻塞等问题
  16. * 如果发现业务卡死,可以将下面declare打开(去掉//注释),并执行php start.php reload
  17. * 然后观察一段时间workerman.log看是否有process_timeout异常
  18. */
  19. //declare(ticks=1);
  20. use \GatewayWorker\Lib\Gateway;
  21. use Workerman\Lib\Timer;
  22. /**
  23. * 主逻辑
  24. * 主要是处理 onConnect onMessage onClose 三个方法
  25. * onConnect 和 onClose 如果不需要可以不用实现并删除
  26. */
  27. class Events
  28. {
  29. /**
  30. * 新建一个类的静态成员,用来保存数据库实例
  31. */
  32. public static $db = null;
  33. public static $global = null;
  34. /**
  35. * 进程启动后初始化数据库连接
  36. */
  37. public static function onWorkerStart($worker)
  38. {
  39. if (empty(self::$db)) {
  40. self::$db = new \Workerman\MySQL\Connection('192.168.2.186', '3306', 'root', '', 'customer_service');
  41. }
  42. if (empty(self::$global)) {
  43. self::$global = new \GlobalData\Client('127.0.0.1:2207');
  44. // 客服列表
  45. if(is_null(self::$global->kfList)){
  46. self::$global->kfList = [];
  47. }
  48. // 会员列表[动态的,这里面只是目前未被分配的会员信息]
  49. if(is_null(self::$global->userList)){
  50. self::$global->userList = [];
  51. }
  52. // 会员以 uid 为key的信息简表,只有在用户退出的时候,才去执行修改
  53. if(is_null(self::$global->uidSimpleList)){
  54. self::$global->uidSimpleList = [];
  55. }
  56. // 当天的累积接入值
  57. $key = date('Ymd') . 'total_in';
  58. if(is_null(self::$global->$key)){
  59. self::$global->$key = 0;
  60. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  61. unset(self::$global->$oldKey);
  62. unset($oldKey, $key);
  63. }
  64. // 成功接入值
  65. $key = date('Ymd') . 'success_in';
  66. if(is_null(self::$global->$key)){
  67. self::$global->$key = 0;
  68. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  69. unset(self::$global->$oldKey);
  70. unset($oldKey, $key);
  71. }
  72. }
  73. // 定时统计数据
  74. if(0 === $worker->id){
  75. // 1分钟统计一次实时数据
  76. Timer::add(60 * 1, function(){
  77. self::writeLog(1);
  78. });
  79. // 40分钟写一次当前日期点数的log数据
  80. Timer::add(60 * 40, function(){
  81. self::writeLog(2);
  82. });
  83. }
  84. }
  85. /**
  86. * 当客户端连接时触发
  87. * 如果业务不需此回调可以删除onConnect
  88. *
  89. * @param int $client_id 连接id
  90. */
  91. public static function onConnect($client_id)
  92. {
  93. // 检测是否开启自动应答
  94. $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 1');
  95. if(!empty($sayHello) && 1 == $sayHello['0']['status']){
  96. $hello = [
  97. 'message_type' => 'helloMessage',
  98. 'data' => [
  99. 'name' => '智能助手',
  100. 'time' => date('H:i'),
  101. 'content' => htmlspecialchars($sayHello['0']['word'])
  102. ]
  103. ];
  104. Gateway::sendToClient($client_id, json_encode($hello));
  105. unset($hello);
  106. }
  107. unset($sayHello);
  108. }
  109. /**
  110. * 当客户端发来消息时触发
  111. * @param int $client_id 连接id
  112. * @param mixed $message 具体消息
  113. */
  114. public static function onMessage($client_id, $message)
  115. {
  116. if ($message!='{"type":"ping"}'){
  117. echo "onMessage: ".$message."\r\n";
  118. // print_r([self::$global->kfList,self::$global->userList, self::$global->uidSimpleList]);
  119. }
  120. $message = json_decode($message, true);
  121. switch ($message['type']) {
  122. // 客服初始化
  123. case 'init':
  124. $kfList = self::$global->kfList;
  125. // 如果该客服未在内存中记录则记录
  126. if(!isset($kfList[$message['group']]) || !array_key_exists($message['uid'], $kfList[$message['group']])){
  127. do{
  128. $newKfList = $kfList;
  129. $newKfList[$message['group']][$message['uid']] = [
  130. 'id' => $message['uid'],
  131. 'name' => $message['name'],
  132. 'avatar' => $message['avatar'],
  133. 'client_id' => $client_id,
  134. 'task' => 0,
  135. 'user_info' => []
  136. ];
  137. }while(!self::$global->cas('kfList', $kfList, $newKfList));
  138. unset($newKfList, $kfList);
  139. }else if(isset($kfList[$message['group']][$message['uid']])){
  140. do{
  141. $newKfList = $kfList;
  142. $newKfList[$message['group']][$message['uid']]['client_id'] = $client_id;
  143. }while(!self::$global->cas('kfList', $kfList, $newKfList));
  144. unset($newKfList, $kfList);
  145. }
  146. // 绑定 client_id 和 uid
  147. Gateway::bindUid($client_id, $message['uid']);
  148. // TODO 尝试拉取用户来服务 [二期规划]
  149. break;
  150. // 顾客初始化
  151. case 'userInit';
  152. $userList = self::$global->userList;
  153. // 如果该顾客未在内存中记录则记录
  154. if(!array_key_exists($message['uid'], $userList)){
  155. do{
  156. $NewUserList = $userList;
  157. $NewUserList[$message['uid']] = [
  158. 'id' => $message['uid'],
  159. 'name' => $message['name'],
  160. 'avatar' => $message['avatar'],
  161. 'website' => $_SESSION['origin'],//$_SERVER['HTTP_ORIGIN'],
  162. 'browse' => Gateway::browse_info(),
  163. 'system' => Gateway::get_os(),
  164. 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
  165. 'group' => $message['group'],
  166. 'client_id' => $client_id
  167. ];
  168. }while(!self::$global->cas('userList', $userList, $NewUserList));
  169. unset($NewUserList, $userList);
  170. // 维护 UID对应的client_id 数组
  171. do{
  172. $old = $newList = self::$global->uidSimpleList;
  173. $newList[$message['uid']] = [
  174. $client_id,
  175. $message['group']
  176. ];
  177. }while(!self::$global->cas('uidSimpleList', $old, $newList));
  178. unset($old, $newList);
  179. // 写入接入值
  180. $key = date('Ymd') . 'total_in';
  181. self::$global->$key = 0;
  182. do{
  183. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  184. unset(self::$global->$oldKey);
  185. }while(!self::$global->increment($key));
  186. unset($key);
  187. }
  188. // 绑定 client_id 和 uid
  189. Gateway::bindUid($client_id, $message['uid']);
  190. // 尝试分配新会员进入服务
  191. self::userOnlineTask($client_id, $message['group']);
  192. break;
  193. // 聊天
  194. case 'chatMessage':
  195. $client = Gateway::getClientIdByUid($message['data']['to_id']);
  196. if(!empty($client)){
  197. $chat_message = [
  198. 'message_type' => 'chatMessage',
  199. 'data' => [
  200. 'name' => $message['data']['from_name'],
  201. 'avatar' => $message['data']['from_avatar'],
  202. 'id' => $message['data']['from_id'],
  203. 'time' => date('H:i'),
  204. 'content' => htmlspecialchars($message['data']['content']),
  205. ]
  206. ];
  207. Gateway::sendToClient($client['0'], json_encode($chat_message));
  208. unset($chat_message);
  209. // 聊天信息入库
  210. $serviceLog = [
  211. 'from_id' => $message['data']['from_id'],
  212. 'from_name' => $message['data']['from_name'],
  213. 'from_avatar' => $message['data']['from_avatar'],
  214. 'to_id' => $message['data']['to_id'],
  215. 'to_name' => $message['data']['to_name'],
  216. 'content' => $message['data']['content'],
  217. 'time_line' => time()
  218. ];
  219. self::$db->insert('ws_chat_log')->cols($serviceLog)->query();
  220. unset($serviceLog);
  221. }
  222. break;
  223. // 转接
  224. case 'changeGroup':
  225. // 通知客户端转接中
  226. $simpleList = self::$global->uidSimpleList;
  227. if(!isset($simpleList[$message['uid']])){ // 客户已经退出
  228. return ;
  229. }
  230. $userClient = $simpleList[$message['uid']]['0'];
  231. $userGroup = $simpleList[$message['uid']]['1']; // 会员原来的分组也是客服的分组
  232. $reLink = [
  233. 'message_type' => 'relinkMessage'
  234. ];
  235. Gateway::sendToClient($userClient, json_encode($reLink));
  236. unset($reLink);
  237. // 记录该客服与该会员的服务结束
  238. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $userClient . "'");
  239. // 从当前客服的服务表中删除这个会员
  240. $old = $kfList = self::$global->kfList;
  241. if(!isset($kfList[$userGroup])){
  242. $waitMsg = '暂时没有相关客服上班,请稍后再咨询。';
  243. // 逐一通知
  244. foreach(self::$global->userList as $vo){
  245. $waitMessage = [
  246. 'message_type' => 'wait',
  247. 'data' => [
  248. 'content' => $waitMsg,
  249. ]
  250. ];
  251. Gateway::sendToClient($userClient, json_encode($waitMessage));
  252. unset($waitMessage);
  253. }
  254. return ;
  255. }
  256. $myList = $kfList[$userGroup]; // 该客服分组数组
  257. foreach($myList as $key=>$vo){
  258. if(in_array($userClient, $vo['user_info'])){
  259. // 维护现在的该客服的服务信息
  260. $kfList[$userGroup][$key]['task'] -= 1; // 当前服务的人数 -1
  261. foreach($vo['user_info'] as $k=>$v){
  262. if($userClient == $v){
  263. unset($kfList[$userGroup][$key]['user_info'][$k]);
  264. break;
  265. }
  266. }
  267. break;
  268. }
  269. }
  270. while(!self::$global->cas('kfList', $old, $kfList)){}; // 刷新内存中客服的服务列表
  271. unset($old, $kfList, $myList);
  272. // 将会员加入队列中
  273. $userList = self::$global->userList;
  274. do{
  275. $NewUserList = $userList;
  276. $NewUserList[$message['uid']] = [
  277. 'id' => $message['uid'],
  278. 'name' => $message['name'],
  279. 'avatar' => $message['avatar'],
  280. 'ip' => $message['ip'],
  281. 'group' => $message['group'], // 指定要链接的分组
  282. 'client_id' => $userClient
  283. ];
  284. }while(!self::$global->cas('userList', $userList, $NewUserList));
  285. unset($NewUserList, $userList);
  286. // 执行会员分配通知双方
  287. self::userOnlineTask($userClient, $message['group']);
  288. unset($userClient, $userGroup);
  289. break;
  290. case 'closeUser':
  291. $userInfo = self::$global->uidSimpleList;
  292. if(isset($userInfo[$message['uid']])){
  293. $waitMessage = [
  294. 'message_type' => 'wait',
  295. 'data' => [
  296. 'content' => '暂时没有客服上班,请稍后再咨询。',
  297. ]
  298. ];
  299. Gateway::sendToClient($userInfo[$message['uid']]['0'], json_encode($waitMessage));
  300. unset($waitMessage);
  301. }
  302. unset($userInfo);
  303. break;
  304. // 机器人问答.
  305. case 'toRobot':
  306. self::toRobot($client_id, $message);
  307. break;
  308. // 评价.
  309. case 'evaluate':
  310. self::evaluate($client_id, $message);
  311. break;
  312. // 客服关闭会话.
  313. case 'kfCloseUser':
  314. $client = Gateway::getClientIdByUid($message['data']['to_id']);
  315. if(!empty($client)){
  316. self::serverClose($client['0']);
  317. }
  318. break;
  319. }
  320. }
  321. /**
  322. * 当用户断开连接时触发
  323. * @param int $client_id 连接id
  324. *
  325. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  326. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  327. */
  328. public static function onClose($client_id)
  329. {
  330. $uidSimpleList = self::$global->uidSimpleList;
  331. $userId = '';
  332. foreach ($uidSimpleList as $k => $v) {
  333. if ($v[0] == $client_id) {
  334. $userId = $k;
  335. }
  336. }
  337. $kfId = '';
  338. if ($userId) {
  339. $userToKf = self::$global->userToKf;
  340. $kfId = $userToKf[$userId][1];
  341. }
  342. if ($kfId) {
  343. $client = Gateway::getClientIdByUid($kfId);
  344. // 返回.
  345. $chat_message = [
  346. 'message_type' => 'userClose',
  347. 'data' => [
  348. 'content' => '用户连接已断开',
  349. 'time' => date('H:i'),
  350. ]
  351. ];
  352. self::$db->query("update `ws_service_log` set `status` = '3' where `client_id`= '" . $client_id . "'");
  353. Gateway::sendToClient($client['0'], json_encode($chat_message));
  354. }
  355. }
  356. /**
  357. * 客服结束会话
  358. * @param int $client_id 连接id
  359. *
  360. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  361. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  362. */
  363. public static function serverClose($client_id)
  364. {
  365. // 返回.
  366. $chat_message = [
  367. 'message_type' => 'closeBysever',
  368. 'data' => [
  369. 'content' => '客服停止了该会话',
  370. 'time' => date('H:i'),
  371. ]
  372. ];
  373. Gateway::sendToClient($client_id, json_encode($chat_message));
  374. $isServiceUserOut = false;
  375. // 将会员服务信息,从客服的服务列表中移除
  376. $old = $kfList = self::$global->kfList;
  377. foreach($kfList as $k=>$v){
  378. foreach($v as $key=>$vo){
  379. if(in_array($client_id, $vo['user_info'])){
  380. $isServiceUserOut = true;
  381. // 根据client id 去更新会话工单一些信息
  382. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $client_id . "'");
  383. // 从会员的内存表中检索出该会员的信息,并更新内存
  384. $oldSimple = $simpleList = self::$global->uidSimpleList;
  385. $outUser = [];
  386. foreach($simpleList as $u=>$c){
  387. if($c['0'] == $client_id){
  388. $outUser[] = [
  389. 'user_id' => $u,
  390. 'group_id' => $c['1']
  391. ];
  392. unset($simpleList[$u]);
  393. break;
  394. }
  395. }
  396. while(!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)){};
  397. unset($oldSimple, $simpleList);
  398. $outUser = self::$db->query("select `user_id`,`group_id` from `ws_service_log` where `client_id`= '" . $client_id . "'");
  399. // 通知 客服删除退出的用户
  400. if(!empty($outUser)){
  401. $del_message = [
  402. 'message_type' => 'delUser',
  403. 'data' => [
  404. 'id' => $outUser['0']['user_id']
  405. ]
  406. ];
  407. Gateway::sendToClient($vo['client_id'], json_encode($del_message));
  408. unset($del_message);
  409. // 尝试分配新会员进入服务
  410. self::userOfflineTask($outUser['0']['group_id']);
  411. }
  412. unset($outUser);
  413. // 维护现在的该客服的服务信息
  414. $kfList[$k][$key]['task'] -= 1; // 当前服务的人数 -1
  415. foreach($vo['user_info'] as $m=>$l){
  416. if($client_id == $l){
  417. unset($kfList[$k][$key]['user_info'][$m]);
  418. break;
  419. }
  420. }
  421. // 刷新内存中客服的服务列表
  422. while(!self::$global->cas('kfList', $old, $kfList)){};
  423. unset($old, $kfList);
  424. break;
  425. }
  426. }
  427. if($isServiceUserOut) break;
  428. }
  429. // 尝试从排队的用户中删除退出的客户端
  430. if(false == $isServiceUserOut){
  431. $old = $userList = self::$global->userList;
  432. foreach(self::$global->userList as $key=>$vo){
  433. if($client_id == $vo['client_id']){
  434. $isServiceUserOut = true;
  435. unset($userList[$key]);
  436. break;
  437. }
  438. }
  439. while(!self::$global->cas('userList', $old, $userList)){};
  440. // 从会员的内存表中检索出该会员的信息,并更新内存
  441. $oldSimple = $simpleList = self::$global->uidSimpleList;
  442. foreach($simpleList as $u=>$c){
  443. if($c['0'] == $client_id){
  444. unset($simpleList[$u]);
  445. break;
  446. }
  447. }
  448. while(!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)){};
  449. unset($oldSimple, $simpleList);
  450. }
  451. // 尝试是否是客服退出
  452. if(false == $isServiceUserOut){
  453. $old = $kfList = self::$global->kfList;
  454. foreach(self::$global->kfList as $k=>$v){
  455. foreach($v as $key=>$vo){
  456. // 客服服务列表中无数据,才去删除客服内存信息
  457. if($client_id == $vo['client_id'] && (0 == count($vo['user_info']))){
  458. unset($kfList[$k][$key]);
  459. break;
  460. }
  461. }
  462. }
  463. while(!self::$global->cas('kfList', $old, $kfList)){};
  464. }
  465. }
  466. /**
  467. * 有人退出
  468. * @param $group
  469. */
  470. private static function userOfflineTask($group)
  471. {
  472. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  473. $maxNumber = self::getMaxServiceNum();
  474. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
  475. unset($maxNumber);
  476. if(1 == $res['code']){
  477. while(!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])){}; // 更新客服数据
  478. while(!self::$global->cas('userList', self::$global->userList, $res['data']['5'])){}; // 更新会员数据
  479. // 通知会员发送信息绑定客服的id
  480. $noticeUser = [
  481. 'message_type' => 'connect',
  482. 'data' => [
  483. 'kf_id' => $res['data']['0'],
  484. 'kf_name' => $res['data']['1']
  485. ]
  486. ];
  487. Gateway::sendToClient($res['data']['3']['client_id'], json_encode($noticeUser));
  488. unset($noticeUser);
  489. // 通知客服端绑定会员的信息
  490. $noticeKf = [
  491. 'message_type' => 'connect',
  492. 'data' => [
  493. 'user_info' => $res['data']['3']
  494. ]
  495. ];
  496. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf));
  497. unset($noticeKf);
  498. // 逐一通知
  499. $number = 1;
  500. foreach(self::$global->userList as $vo){
  501. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  502. $waitMessage = [
  503. 'message_type' => 'wait',
  504. 'data' => [
  505. 'content' => $waitMsg,
  506. ]
  507. ];
  508. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage));
  509. $number++;
  510. }
  511. unset($waitMessage, $number);
  512. // 写入接入值
  513. $key = date('Ymd') . 'success_in';
  514. self::$global->$key = 0;
  515. do{
  516. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  517. unset(self::$global->$oldKey);
  518. }while(!self::$global->increment($key));
  519. unset($key);
  520. }else{
  521. switch ($res['code']){
  522. case -1:
  523. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  524. // 逐一通知
  525. foreach(self::$global->userList as $vo){
  526. $waitMessage = [
  527. 'message_type' => 'wait',
  528. 'data' => [
  529. 'content' => $waitMsg,
  530. ]
  531. ];
  532. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage));
  533. }
  534. break;
  535. case -2:
  536. break;
  537. case -3:
  538. break;
  539. case -4:
  540. // 逐一通知
  541. $number = 1;
  542. foreach(self::$global->userList as $vo){
  543. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  544. $waitMessage = [
  545. 'message_type' => 'wait',
  546. 'data' => [
  547. 'content' => $waitMsg,
  548. ]
  549. ];
  550. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage));
  551. $number++;
  552. }
  553. break;
  554. }
  555. unset($waitMessage, $number);
  556. }
  557. }
  558. /**
  559. * 有人进入执行分配
  560. * @param $client_id
  561. * @param $group
  562. */
  563. private static function userOnlineTask($client_id, $group)
  564. {
  565. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  566. $maxNumber = self::getMaxServiceNum();
  567. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
  568. unset($maxNumber);
  569. if(1 == $res['code']){
  570. while(!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])){}; // 更新客服数据
  571. while(!self::$global->cas('userList', self::$global->userList, $res['data']['5'])){}; // 更新会员数据
  572. $userToKf = self::$global->userToKf;
  573. $userToKf[$res['data']['3']['id']] = [
  574. $res['data']['3']['id'],
  575. $res['data']['0']
  576. ];
  577. self::$global->userToKf = $userToKf;
  578. // 通知会员发送信息绑定客服的id
  579. $noticeUser = [
  580. 'message_type' => 'connect',
  581. 'data' => [
  582. 'kf_id' => $res['data']['0'],
  583. 'kf_name' => $res['data']['1']
  584. ]
  585. ];
  586. Gateway::sendToClient($client_id, json_encode($noticeUser));
  587. unset($noticeUser);
  588. // 通知客服端绑定会员的信息
  589. $noticeKf = [
  590. 'message_type' => 'connect',
  591. 'data' => [
  592. 'user_info' => $res['data']['3']
  593. ]
  594. ];
  595. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf));
  596. unset($noticeKf);
  597. // 服务信息入库
  598. $serviceLog = [
  599. 'user_id' => $res['data']['3']['id'],
  600. 'client_id' => $res['data']['3']['client_id'],
  601. 'user_name' => $res['data']['3']['name'],
  602. 'user_ip' => $res['data']['3']['ip'],
  603. 'user_avatar' => $res['data']['3']['avatar'],
  604. 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
  605. 'start_time' => time(),
  606. 'group_id' => $group,
  607. 'website' => $res['data']['3']['website'],
  608. 'system' => $res['data']['3']['system'],
  609. 'browse' => $res['data']['3']['browse'],
  610. 'status' => 1,
  611. 'end_time' => 0
  612. ];
  613. self::$db->insert('ws_service_log')->cols($serviceLog)->query();
  614. unset($serviceLog);
  615. // 写入接入值
  616. $key = date('Ymd') . 'success_in';
  617. self::$global->$key = 0;
  618. do{
  619. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  620. unset(self::$global->$oldKey);
  621. }while(!self::$global->increment($key));
  622. unset($key);
  623. }else{
  624. $waitMsg = '';
  625. switch ($res['code']){
  626. case -1:
  627. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  628. break;
  629. case -2:
  630. break;
  631. case -3:
  632. break;
  633. case -4:
  634. $number = count(self::$global->userList);
  635. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  636. break;
  637. }
  638. $waitMessage = [
  639. 'message_type' => 'wait',
  640. 'data' => [
  641. 'content' => $waitMsg,
  642. ]
  643. ];
  644. Gateway::sendToClient($client_id, json_encode($waitMessage));
  645. unset($waitMessage);
  646. }
  647. }
  648. /**
  649. * 给客服分配会员【均分策略】
  650. * @param $kfList
  651. * @param $userList
  652. * @param $group
  653. * @param $total
  654. */
  655. private static function assignmentTask($kfList, $userList, $group, $total)
  656. {
  657. // 没有客服上线
  658. if(empty($kfList) || empty($kfList[$group])){
  659. return ['code' => -1];
  660. }
  661. // 没有待分配的会员
  662. if(empty($userList)){
  663. return ['code' => -2];
  664. }
  665. // 未设置每个客服可以服务多少人
  666. if(0 == $total){
  667. return ['code' => -3];
  668. }
  669. // 查看该组的客服是否在线
  670. if(!isset($kfList[$group])){
  671. return ['code' => -1];
  672. }
  673. $kf = $kfList[$group];
  674. $user = array_shift($userList);
  675. $kf = array_shift($kf);
  676. $min = $kf['task'];
  677. $flag = $kf['id'];
  678. foreach($kfList[$group] as $key=>$vo){
  679. if($vo['task'] < $min){
  680. $min = $vo['task'];
  681. $flag = $key;
  682. }
  683. }
  684. unset($kf);
  685. // 需要排队了
  686. if($kfList[$group][$flag]['task'] == $total){
  687. return ['code' => -4];
  688. }
  689. $kfList[$group][$flag]['task'] += 1;
  690. array_push($kfList[$group][$flag]['user_info'], $user['client_id']); // 被分配的用户信息
  691. return [
  692. 'code' => 1,
  693. 'data' => [
  694. $kfList[$group][$flag]['id'],
  695. $kfList[$group][$flag]['name'],
  696. $kfList[$group][$flag]['client_id'],
  697. $user,
  698. $kfList,
  699. $userList
  700. ]
  701. ];
  702. }
  703. /**
  704. * 获取最大的服务人数
  705. * @return int
  706. */
  707. private static function getMaxServiceNum()
  708. {
  709. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  710. if(!empty($maxNumber)){
  711. $maxNumber = 5;
  712. }else{
  713. $maxNumber = $maxNumber['0']['max_service'];
  714. }
  715. return $maxNumber;
  716. }
  717. /**
  718. * 将内存中的数据写入统计表
  719. * @param int $flag
  720. */
  721. private static function writeLog($flag = 1)
  722. {
  723. // 上午 8点 到 22 点开始统计
  724. if(date('H') < 8 || date('H') > 22){
  725. return ;
  726. }
  727. // 当前正在接入的人 和 在线客服数
  728. $kfList = self::$global->kfList;
  729. $nowTalking = 0;
  730. $onlineKf = 0;
  731. if(!empty($kfList)){
  732. foreach($kfList as $key=>$vo){
  733. $onlineKf += count($vo);
  734. foreach($vo as $k=>$v){
  735. $nowTalking += count($v['user_info']);
  736. }
  737. }
  738. }
  739. // 在队列中的用户
  740. $inQueue = count(self::$global->userList);
  741. $key = date('Ymd') . 'total_in';
  742. $key2 = date('Ymd') . 'success_in';
  743. $param = [
  744. 'is_talking' => $nowTalking,
  745. 'in_queue' => $inQueue,
  746. 'online_kf' => $onlineKf,
  747. 'success_in' => self::$global->$key2,
  748. 'total_in' => self::$global->$key,
  749. 'now_date' => date('Y-m-d')
  750. ];
  751. self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
  752. if(2 == $flag){
  753. $param = [
  754. 'is_talking' => $nowTalking,
  755. 'in_queue' => $inQueue,
  756. 'online_kf' => $onlineKf,
  757. 'success_in' => self::$global->$key2,
  758. 'total_in' => self::$global->$key,
  759. 'add_date' => date('Y-m-d'),
  760. 'add_hour' => date('H'),
  761. 'add_minute' => date('i'),
  762. ];
  763. self::$db->insert('ws_service_data')->cols($param)->query();
  764. }
  765. unset($kfList, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
  766. }
  767. /**
  768. * 机器人问答
  769. * @param $client_id 服务ID
  770. * @param $message 数据
  771. */
  772. private static function toRobot($client_id, $message)
  773. {
  774. $groups_id = $message['data']['groups_id'];
  775. $robot_name = $message['data']['robot_name'];
  776. $robotgroups_id = $message['data']['robotgroups_id'];
  777. // 查询问题.
  778. $getRobot = self::$db->query("select `robot_content` from `ws_robot` where `robot_status`= 1 and `groups_id`= '" . $groups_id . "' and `robot_name`= '" . $robot_name . "' and `robotgroups_id`= '" . $robotgroups_id . "'");
  779. $chat_message = [
  780. 'message_type' => 'chatMessage',
  781. 'data' => [
  782. 'name' => '智能助手',
  783. 'time' => date('H:i'),
  784. 'content' => $getRobot ? htmlspecialchars($getRobot[0]['robot_content']) : 'error',
  785. ]
  786. ];
  787. Gateway::sendToClient($client_id, json_encode($chat_message));
  788. }
  789. /**
  790. * 评价
  791. * @param $client_id 服务ID
  792. * @param $message 数据
  793. */
  794. private static function evaluate($client_id, $message)
  795. {
  796. // 修改数据库.
  797. $evaluate_id = $message['data']['evaluate_id'];
  798. $result = self::$db->query("UPDATE `ws_service_log` SET `evaluate_id` = '" . $evaluate_id . "' WHERE `client_id`='" . $client_id . "'");
  799. if ($result) {
  800. $chat_message = [
  801. 'message_type' => 'evaluate',
  802. 'data' => [
  803. 'status' => 1,
  804. 'time' => date('H:i'),
  805. ]
  806. ];
  807. } else {
  808. $chat_message = [
  809. 'message_type' => 'evaluate',
  810. 'data' => [
  811. 'status' => 2,
  812. 'time' => date('H:i'),
  813. ]
  814. ];
  815. }
  816. Gateway::sendToClient($client_id, json_encode($chat_message));
  817. }
  818. }