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