Events.php 34 KB

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