Events.php 32 KB

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