Events.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  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 'closeUser':
  299. $client = Gateway::getClientIdByUid($message['data']['to_id']);
  300. if(!empty($client)){
  301. self::onClose($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. print_r([$client_id,self::$global->uidSimpleList,self::$global->userList]);
  316. $isServiceUserOut = false;
  317. // 将会员服务信息,从客服的服务列表中移除
  318. $old = $kfList = self::$global->kfList;
  319. foreach($kfList as $k=>$v){
  320. foreach($v as $key=>$vo){
  321. if(in_array($client_id, $vo['user_info'])){
  322. $isServiceUserOut = true;
  323. // 根据client id 去更新这个会员离线的一些信息
  324. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $client_id . "'");
  325. // 从会员的内存表中检索出该会员的信息,并更新内存
  326. $oldSimple = $simpleList = self::$global->uidSimpleList;
  327. $outUser = [];
  328. foreach($simpleList as $u=>$c){
  329. if($c['0'] == $client_id){
  330. $outUser[] = [
  331. 'user_id' => $u,
  332. 'group_id' => $c['1']
  333. ];
  334. unset($simpleList[$u]);
  335. break;
  336. }
  337. }
  338. while(!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)){};
  339. unset($oldSimple, $simpleList);
  340. //$outUser = self::$db->query("select `user_id`,`group_id` from `ws_service_log` where `client_id`= '" . $client_id . "'");
  341. // 通知 客服删除退出的用户
  342. if(!empty($outUser)){
  343. $del_message = [
  344. 'message_type' => 'delUser',
  345. 'data' => [
  346. 'id' => $outUser['0']['user_id']
  347. ]
  348. ];
  349. Gateway::sendToClient($vo['client_id'], json_encode($del_message));
  350. unset($del_message);
  351. // 尝试分配新会员进入服务
  352. self::userOfflineTask($outUser['0']['group_id']);
  353. }
  354. unset($outUser);
  355. // 维护现在的该客服的服务信息
  356. $kfList[$k][$key]['task'] -= 1; // 当前服务的人数 -1
  357. foreach($vo['user_info'] as $m=>$l){
  358. if($client_id == $l){
  359. unset($kfList[$k][$key]['user_info'][$m]);
  360. break;
  361. }
  362. }
  363. // 刷新内存中客服的服务列表
  364. while(!self::$global->cas('kfList', $old, $kfList)){};
  365. unset($old, $kfList);
  366. break;
  367. }
  368. }
  369. if($isServiceUserOut) break;
  370. }
  371. // 尝试从排队的用户中删除退出的客户端
  372. if(false == $isServiceUserOut){
  373. $old = $userList = self::$global->userList;
  374. foreach(self::$global->userList as $key=>$vo){
  375. if($client_id == $vo['client_id']){
  376. $isServiceUserOut = true;
  377. unset($userList[$key]);
  378. break;
  379. }
  380. }
  381. while(!self::$global->cas('userList', $old, $userList)){};
  382. // 从会员的内存表中检索出该会员的信息,并更新内存
  383. $oldSimple = $simpleList = self::$global->uidSimpleList;
  384. foreach($simpleList as $u=>$c){
  385. if($c['0'] == $client_id){
  386. unset($simpleList[$u]);
  387. break;
  388. }
  389. }
  390. while(!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)){};
  391. unset($oldSimple, $simpleList);
  392. }
  393. // 尝试是否是客服退出
  394. if(false == $isServiceUserOut){
  395. $old = $kfList = self::$global->kfList;
  396. foreach(self::$global->kfList as $k=>$v){
  397. foreach($v as $key=>$vo){
  398. // 客服服务列表中无数据,才去删除客服内存信息
  399. if($client_id == $vo['client_id'] && (0 == count($vo['user_info']))){
  400. unset($kfList[$k][$key]);
  401. break;
  402. }
  403. }
  404. }
  405. while(!self::$global->cas('kfList', $old, $kfList)){};
  406. }
  407. }
  408. /**
  409. * 有人退出
  410. * @param $group
  411. */
  412. private static function userOfflineTask($group)
  413. {
  414. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  415. $maxNumber = self::getMaxServiceNum();
  416. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
  417. unset($maxNumber);
  418. if(1 == $res['code']){
  419. while(!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])){}; // 更新客服数据
  420. while(!self::$global->cas('userList', self::$global->userList, $res['data']['5'])){}; // 更新会员数据
  421. // 通知会员发送信息绑定客服的id
  422. $noticeUser = [
  423. 'message_type' => 'connect',
  424. 'data' => [
  425. 'kf_id' => $res['data']['0'],
  426. 'kf_name' => $res['data']['1']
  427. ]
  428. ];
  429. Gateway::sendToClient($res['data']['3']['client_id'], json_encode($noticeUser));
  430. unset($noticeUser);
  431. // 通知客服端绑定会员的信息
  432. $noticeKf = [
  433. 'message_type' => 'connect',
  434. 'data' => [
  435. 'user_info' => $res['data']['3']
  436. ]
  437. ];
  438. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf));
  439. unset($noticeKf);
  440. // 逐一通知
  441. $number = 1;
  442. foreach(self::$global->userList as $vo){
  443. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  444. $waitMessage = [
  445. 'message_type' => 'wait',
  446. 'data' => [
  447. 'content' => $waitMsg,
  448. ]
  449. ];
  450. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage));
  451. $number++;
  452. }
  453. unset($waitMessage, $number);
  454. // 写入接入值
  455. $key = date('Ymd') . 'success_in';
  456. self::$global->$key = 0;
  457. do{
  458. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  459. unset(self::$global->$oldKey);
  460. }while(!self::$global->increment($key));
  461. unset($key);
  462. }else{
  463. switch ($res['code']){
  464. case -1:
  465. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  466. // 逐一通知
  467. foreach(self::$global->userList as $vo){
  468. $waitMessage = [
  469. 'message_type' => 'wait',
  470. 'data' => [
  471. 'content' => $waitMsg,
  472. ]
  473. ];
  474. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage));
  475. }
  476. break;
  477. case -2:
  478. break;
  479. case -3:
  480. break;
  481. case -4:
  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. break;
  496. }
  497. unset($waitMessage, $number);
  498. }
  499. }
  500. /**
  501. * 有人进入执行分配
  502. * @param $client_id
  503. * @param $group
  504. */
  505. private static function userOnlineTask($client_id, $group)
  506. {
  507. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  508. $maxNumber = self::getMaxServiceNum();
  509. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
  510. unset($maxNumber);
  511. if(1 == $res['code']){
  512. while(!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])){}; // 更新客服数据
  513. while(!self::$global->cas('userList', self::$global->userList, $res['data']['5'])){}; // 更新会员数据
  514. // 通知会员发送信息绑定客服的id
  515. $noticeUser = [
  516. 'message_type' => 'connect',
  517. 'data' => [
  518. 'kf_id' => $res['data']['0'],
  519. 'kf_name' => $res['data']['1']
  520. ]
  521. ];
  522. Gateway::sendToClient($client_id, json_encode($noticeUser));
  523. unset($noticeUser);
  524. // 检测是否开启自动应答
  525. $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 1');
  526. if(!empty($sayHello) && 1 == $sayHello['0']['status']){
  527. $hello = [
  528. 'message_type' => 'helloMessage',
  529. 'data' => [
  530. 'name' => $res['data']['1'],
  531. 'avatar' => '',
  532. 'id' => $res['data']['0'],
  533. 'time' => date('H:i'),
  534. 'content' => htmlspecialchars($sayHello['0']['word'])
  535. ]
  536. ];
  537. Gateway::sendToClient($client_id, json_encode($hello));
  538. unset($hello);
  539. }
  540. unset($sayHello);
  541. // 通知客服端绑定会员的信息
  542. $noticeKf = [
  543. 'message_type' => 'connect',
  544. 'data' => [
  545. 'user_info' => $res['data']['3']
  546. ]
  547. ];
  548. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf));
  549. unset($noticeKf);
  550. // 服务信息入库
  551. $serviceLog = [
  552. 'user_id' => $res['data']['3']['id'],
  553. 'client_id' => $res['data']['3']['client_id'],
  554. 'user_name' => $res['data']['3']['name'],
  555. 'user_ip' => $res['data']['3']['ip'],
  556. 'user_avatar' => $res['data']['3']['avatar'],
  557. 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
  558. 'start_time' => time(),
  559. 'group_id' => $group,
  560. 'website' => $res['data']['3']['website'],
  561. 'system' => $res['data']['3']['system'],
  562. 'browse' => $res['data']['3']['browse'],
  563. 'status' => 1,
  564. 'end_time' => 0
  565. ];
  566. self::$db->insert('ws_service_log')->cols($serviceLog)->query();
  567. unset($serviceLog);
  568. // 写入接入值
  569. $key = date('Ymd') . 'success_in';
  570. self::$global->$key = 0;
  571. do{
  572. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  573. unset(self::$global->$oldKey);
  574. }while(!self::$global->increment($key));
  575. unset($key);
  576. }else{
  577. $waitMsg = '';
  578. switch ($res['code']){
  579. case -1:
  580. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  581. break;
  582. case -2:
  583. break;
  584. case -3:
  585. break;
  586. case -4:
  587. $number = count(self::$global->userList);
  588. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  589. break;
  590. }
  591. $waitMessage = [
  592. 'message_type' => 'wait',
  593. 'data' => [
  594. 'content' => $waitMsg,
  595. ]
  596. ];
  597. Gateway::sendToClient($client_id, json_encode($waitMessage));
  598. unset($waitMessage);
  599. }
  600. }
  601. /**
  602. * 给客服分配会员【均分策略】
  603. * @param $kfList
  604. * @param $userList
  605. * @param $group
  606. * @param $total
  607. */
  608. private static function assignmentTask($kfList, $userList, $group, $total)
  609. {
  610. // 没有客服上线
  611. if(empty($kfList) || empty($kfList[$group])){
  612. return ['code' => -1];
  613. }
  614. // 没有待分配的会员
  615. if(empty($userList)){
  616. return ['code' => -2];
  617. }
  618. // 未设置每个客服可以服务多少人
  619. if(0 == $total){
  620. return ['code' => -3];
  621. }
  622. // 查看该组的客服是否在线
  623. if(!isset($kfList[$group])){
  624. return ['code' => -1];
  625. }
  626. $kf = $kfList[$group];
  627. $user = array_shift($userList);
  628. $kf = array_shift($kf);
  629. $min = $kf['task'];
  630. $flag = $kf['id'];
  631. foreach($kfList[$group] as $key=>$vo){
  632. if($vo['task'] < $min){
  633. $min = $vo['task'];
  634. $flag = $key;
  635. }
  636. }
  637. unset($kf);
  638. // 需要排队了
  639. if($kfList[$group][$flag]['task'] == $total){
  640. return ['code' => -4];
  641. }
  642. $kfList[$group][$flag]['task'] += 1;
  643. array_push($kfList[$group][$flag]['user_info'], $user['client_id']); // 被分配的用户信息
  644. return [
  645. 'code' => 1,
  646. 'data' => [
  647. $kfList[$group][$flag]['id'],
  648. $kfList[$group][$flag]['name'],
  649. $kfList[$group][$flag]['client_id'],
  650. $user,
  651. $kfList,
  652. $userList
  653. ]
  654. ];
  655. }
  656. /**
  657. * 获取最大的服务人数
  658. * @return int
  659. */
  660. private static function getMaxServiceNum()
  661. {
  662. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  663. if(!empty($maxNumber)){
  664. $maxNumber = 5;
  665. }else{
  666. $maxNumber = $maxNumber['0']['max_service'];
  667. }
  668. return $maxNumber;
  669. }
  670. /**
  671. * 将内存中的数据写入统计表
  672. * @param int $flag
  673. */
  674. private static function writeLog($flag = 1)
  675. {
  676. // 上午 8点 到 22 点开始统计
  677. if(date('H') < 8 || date('H') > 22){
  678. return ;
  679. }
  680. // 当前正在接入的人 和 在线客服数
  681. $kfList = self::$global->kfList;
  682. $nowTalking = 0;
  683. $onlineKf = 0;
  684. if(!empty($kfList)){
  685. foreach($kfList as $key=>$vo){
  686. $onlineKf += count($vo);
  687. foreach($vo as $k=>$v){
  688. $nowTalking += count($v['user_info']);
  689. }
  690. }
  691. }
  692. // 在队列中的用户
  693. $inQueue = count(self::$global->userList);
  694. $key = date('Ymd') . 'total_in';
  695. $key2 = date('Ymd') . 'success_in';
  696. $param = [
  697. 'is_talking' => $nowTalking,
  698. 'in_queue' => $inQueue,
  699. 'online_kf' => $onlineKf,
  700. 'success_in' => self::$global->$key2,
  701. 'total_in' => self::$global->$key,
  702. 'now_date' => date('Y-m-d')
  703. ];
  704. self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
  705. if(2 == $flag){
  706. $param = [
  707. 'is_talking' => $nowTalking,
  708. 'in_queue' => $inQueue,
  709. 'online_kf' => $onlineKf,
  710. 'success_in' => self::$global->$key2,
  711. 'total_in' => self::$global->$key,
  712. 'add_date' => date('Y-m-d'),
  713. 'add_hour' => date('H'),
  714. 'add_minute' => date('i'),
  715. ];
  716. self::$db->insert('ws_service_data')->cols($param)->query();
  717. }
  718. unset($kfList, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
  719. }
  720. /**
  721. * 机器人问答
  722. * @param $client_id 服务ID
  723. * @param $message 数据
  724. */
  725. private static function toRobot($client_id, $message)
  726. {
  727. $groups_id = $message['data']['groups_id'];
  728. $robot_name = $message['data']['robot_name'];
  729. $robotgroups_id = $message['data']['robotgroups_id'];
  730. // 查询问题.
  731. $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 . "'");
  732. $chat_message = [
  733. 'message_type' => 'chatMessage',
  734. 'data' => [
  735. 'name' => '智能助手',
  736. 'time' => date('H:i'),
  737. 'content' => $getRobot ? htmlspecialchars($getRobot[0]['robot_content']) : 'error',
  738. ]
  739. ];
  740. Gateway::sendToClient($client_id, json_encode($chat_message));
  741. }
  742. /**
  743. * 评价
  744. * @param $client_id 服务ID
  745. * @param $message 数据
  746. */
  747. private static function evaluate($client_id, $message)
  748. {
  749. // 查询问题.
  750. $evaluate_id = $message['data']['evaluate_id'];
  751. $result = self::$db->query("UPDATE `ws_service_log` SET `evaluate_id` = '" . $evaluate_id . "' WHERE `client_id`='" . $client_id . "'");
  752. if ($result) {
  753. $chat_message = [
  754. 'message_type' => 'evaluate',
  755. 'data' => [
  756. 'status' => 1,
  757. 'time' => date('H:i'),
  758. ]
  759. ];
  760. } else {
  761. $chat_message = [
  762. 'message_type' => 'evaluate',
  763. 'data' => [
  764. 'status' => 2,
  765. 'time' => date('H:i'),
  766. ]
  767. ];
  768. }
  769. Gateway::sendToClient($client_id, json_encode($chat_message));
  770. }
  771. }