Events.php 34 KB

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