Events.php 30 KB

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