Events.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  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, self::$global->userToKf]);
  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. }; // 刷新内存中客服的服务列表
  276. unset($old, $kfList, $myList);
  277. // 将会员加入队列中
  278. $userList = self::$global->userList;
  279. do {
  280. $NewUserList = $userList;
  281. $NewUserList[$message['uid']] = [
  282. 'id' => $message['uid'],
  283. 'name' => $message['name'],
  284. 'avatar' => $message['avatar'],
  285. 'ip' => $message['ip'],
  286. 'group' => $message['group'], // 指定要链接的分组
  287. 'client_id' => $userClient
  288. ];
  289. } while (!self::$global->cas('userList', $userList, $NewUserList));
  290. unset($NewUserList, $userList);
  291. // 执行会员分配通知双方
  292. self::userOnlineTask($userClient, $message['group']);
  293. unset($userClient, $userGroup);
  294. break;
  295. case 'closeUser':
  296. $userInfo = self::$global->uidSimpleList;
  297. if (isset($userInfo[$message['uid']])) {
  298. $waitMessage = [
  299. 'message_type' => 'wait',
  300. 'data' => [
  301. 'content' => '暂时没有客服上班,请稍后再咨询。',
  302. ]
  303. ];
  304. Gateway::sendToClient($userInfo[$message['uid']]['0'], json_encode($waitMessage));
  305. unset($waitMessage);
  306. }
  307. unset($userInfo);
  308. break;
  309. // 机器人问答.
  310. case 'toRobot':
  311. self::toRobot($client_id, $message);
  312. break;
  313. // 评价.
  314. case 'evaluate':
  315. self::evaluate($client_id, $message);
  316. break;
  317. // 客服关闭会话.
  318. case 'kfCloseUser':
  319. $client = Gateway::getClientIdByUid($message['data']['to_id']);
  320. if (!empty($client)) {
  321. self::serverClose($client['0']);
  322. }
  323. break;
  324. }
  325. }
  326. /**
  327. * 当用户断开连接时触发
  328. * @param int $client_id 连接id
  329. *
  330. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  331. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  332. */
  333. public static function onClose($client_id)
  334. {
  335. $uidSimpleList = self::$global->uidSimpleList;
  336. $userId = '';
  337. foreach ($uidSimpleList as $k => $v) {
  338. if ($v[0] == $client_id) {
  339. $userId = $k;
  340. }
  341. }
  342. $kfId = '';
  343. if ($userId) {
  344. $userToKf = self::$global->userToKf;
  345. $kfId = $userToKf[$userId][1];
  346. }
  347. if ($kfId) {
  348. $client = Gateway::getClientIdByUid($kfId);
  349. // 返回.
  350. $chat_message = [
  351. 'message_type' => 'userClose',
  352. 'data' => [
  353. 'content' => '用户连接已断开',
  354. 'time' => date('H:i'),
  355. ]
  356. ];
  357. self::$db->query("update `ws_service_log` set `status` = '3' where `client_id`= '" . $client_id . "'");
  358. Gateway::sendToClient($client['0'], json_encode($chat_message));
  359. }
  360. }
  361. /**
  362. * 客服结束会话
  363. * @param int $client_id 连接id
  364. *
  365. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  366. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  367. */
  368. public static function serverClose($client_id)
  369. {
  370. // 返回.
  371. $chat_message = [
  372. 'message_type' => 'closeBysever',
  373. 'data' => [
  374. 'content' => '客服停止了该会话',
  375. 'time' => date('H:i'),
  376. ]
  377. ];
  378. Gateway::sendToClient($client_id, json_encode($chat_message));
  379. $isServiceUserOut = false;
  380. // 将会员服务信息,从客服的服务列表中移除
  381. $old = $kfList = self::$global->kfList;
  382. foreach ($kfList as $k => $v) {
  383. foreach ($v as $key => $vo) {
  384. if (in_array($client_id, $vo['user_info'])) {
  385. $isServiceUserOut = true;
  386. // 根据client id 去更新会话工单一些信息
  387. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $client_id . "'");
  388. // 从会员的内存表中检索出该会员的信息,并更新内存
  389. $oldSimple = $simpleList = self::$global->uidSimpleList;
  390. $outUser = [];
  391. foreach ($simpleList as $u => $c) {
  392. if ($c['0'] == $client_id) {
  393. $outUser[] = [
  394. 'user_id' => $u,
  395. 'group_id' => $c['1']
  396. ];
  397. unset($simpleList[$u]);
  398. break;
  399. }
  400. }
  401. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  402. };
  403. unset($oldSimple, $simpleList);
  404. $outUser = self::$db->query("select `user_id`,`group_id` from `ws_service_log` where `client_id`= '" . $client_id . "'");
  405. // 通知 客服删除退出的用户
  406. if (!empty($outUser)) {
  407. $del_message = [
  408. 'message_type' => 'delUser',
  409. 'data' => [
  410. 'id' => $outUser['0']['user_id']
  411. ]
  412. ];
  413. Gateway::sendToClient($vo['client_id'], json_encode($del_message));
  414. unset($del_message);
  415. // 尝试分配新会员进入服务
  416. self::userOfflineTask($outUser['0']['group_id']);
  417. }
  418. unset($outUser);
  419. // 维护现在的该客服的服务信息
  420. $kfList[$k][$key]['task'] -= 1; // 当前服务的人数 -1
  421. foreach ($vo['user_info'] as $m => $l) {
  422. if ($client_id == $l) {
  423. unset($kfList[$k][$key]['user_info'][$m]);
  424. break;
  425. }
  426. }
  427. // 刷新内存中客服的服务列表
  428. while (!self::$global->cas('kfList', $old, $kfList)) {
  429. };
  430. unset($old, $kfList);
  431. break;
  432. }
  433. }
  434. if ($isServiceUserOut) break;
  435. }
  436. // 尝试从排队的用户中删除退出的客户端
  437. if (false == $isServiceUserOut) {
  438. $old = $userList = self::$global->userList;
  439. foreach (self::$global->userList as $key => $vo) {
  440. if ($client_id == $vo['client_id']) {
  441. $isServiceUserOut = true;
  442. unset($userList[$key]);
  443. break;
  444. }
  445. }
  446. while (!self::$global->cas('userList', $old, $userList)) {
  447. };
  448. // 从会员的内存表中检索出该会员的信息,并更新内存
  449. $oldSimple = $simpleList = self::$global->uidSimpleList;
  450. foreach ($simpleList as $u => $c) {
  451. if ($c['0'] == $client_id) {
  452. unset($simpleList[$u]);
  453. break;
  454. }
  455. }
  456. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  457. };
  458. unset($oldSimple, $simpleList);
  459. }
  460. // 尝试是否是客服退出
  461. if (false == $isServiceUserOut) {
  462. $old = $kfList = self::$global->kfList;
  463. foreach (self::$global->kfList as $k => $v) {
  464. foreach ($v as $key => $vo) {
  465. // 客服服务列表中无数据,才去删除客服内存信息
  466. if ($client_id == $vo['client_id'] && (0 == count($vo['user_info']))) {
  467. unset($kfList[$k][$key]);
  468. break;
  469. }
  470. }
  471. }
  472. while (!self::$global->cas('kfList', $old, $kfList)) {
  473. };
  474. }
  475. }
  476. /**
  477. * 有人退出
  478. * @param $group
  479. */
  480. private static function userOfflineTask($group)
  481. {
  482. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  483. $maxNumber = self::getMaxServiceNum();
  484. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
  485. unset($maxNumber);
  486. if (1 == $res['code']) {
  487. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  488. }; // 更新客服数据
  489. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  490. }; // 更新会员数据
  491. // 通知会员发送信息绑定客服的id
  492. $noticeUser = [
  493. 'message_type' => 'connect',
  494. 'data' => [
  495. 'kf_id' => $res['data']['0'],
  496. 'kf_name' => $res['data']['1']
  497. ]
  498. ];
  499. Gateway::sendToClient($res['data']['3']['client_id'], json_encode($noticeUser));
  500. unset($noticeUser);
  501. // 通知客服端绑定会员的信息
  502. $noticeKf = [
  503. 'message_type' => 'connect',
  504. 'data' => [
  505. 'user_info' => $res['data']['3']
  506. ]
  507. ];
  508. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf));
  509. unset($noticeKf);
  510. // 逐一通知
  511. $number = 1;
  512. foreach (self::$global->userList as $vo) {
  513. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  514. $waitMessage = [
  515. 'message_type' => 'wait',
  516. 'data' => [
  517. 'content' => $waitMsg,
  518. ]
  519. ];
  520. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage));
  521. $number++;
  522. }
  523. unset($waitMessage, $number);
  524. // 写入接入值
  525. $key = date('Ymd') . 'success_in';
  526. self::$global->$key = 0;
  527. do {
  528. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  529. unset(self::$global->$oldKey);
  530. } while (!self::$global->increment($key));
  531. unset($key);
  532. } else {
  533. switch ($res['code']) {
  534. case -1:
  535. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  536. // 逐一通知
  537. foreach (self::$global->userList as $vo) {
  538. $waitMessage = [
  539. 'message_type' => 'wait',
  540. 'data' => [
  541. 'content' => $waitMsg,
  542. ]
  543. ];
  544. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage));
  545. }
  546. break;
  547. case -2:
  548. break;
  549. case -3:
  550. break;
  551. case -4:
  552. // 逐一通知
  553. $number = 1;
  554. foreach (self::$global->userList as $vo) {
  555. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  556. $waitMessage = [
  557. 'message_type' => 'wait',
  558. 'data' => [
  559. 'content' => $waitMsg,
  560. ]
  561. ];
  562. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage));
  563. $number++;
  564. }
  565. break;
  566. }
  567. unset($waitMessage, $number);
  568. }
  569. }
  570. /**
  571. * 有人进入执行分配
  572. * @param $client_id
  573. * @param $group
  574. */
  575. private static function userOnlineTask($client_id, $group)
  576. {
  577. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  578. $maxNumber = self::getMaxServiceNum();
  579. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
  580. unset($maxNumber);
  581. if (1 == $res['code']) {
  582. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  583. }; // 更新客服数据
  584. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  585. }; // 更新会员数据
  586. $userToKf = self::$global->userToKf;
  587. $userToKf[$res['data']['3']['id']] = [
  588. $res['data']['3']['id'],
  589. $res['data']['0']
  590. ];
  591. self::$global->userToKf = $userToKf;
  592. // 服务信息入库
  593. $serviceLog = [
  594. 'user_id' => $res['data']['3']['id'],
  595. 'client_id' => $res['data']['3']['client_id'],
  596. 'user_name' => $res['data']['3']['name'],
  597. 'user_ip' => $res['data']['3']['ip'],
  598. 'user_avatar' => $res['data']['3']['avatar'],
  599. 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
  600. 'start_time' => time(),
  601. 'group_id' => $group,
  602. 'website' => $res['data']['3']['website'],
  603. 'system' => $res['data']['3']['system'],
  604. 'browse' => $res['data']['3']['browse'],
  605. 'status' => 1,
  606. 'end_time' => 0
  607. ];
  608. $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
  609. unset($serviceLog);
  610. // 通知会员发送信息绑定客服的id
  611. $noticeUser = [
  612. 'message_type' => 'connect',
  613. 'data' => [
  614. 'kf_id' => $res['data']['0'],
  615. 'conversationId' => $conversationId,
  616. 'kf_name' => $res['data']['1']
  617. ]
  618. ];
  619. Gateway::sendToClient($client_id, json_encode($noticeUser));
  620. unset($noticeUser);
  621. // 通知客服端绑定会员的信息
  622. $noticeKf = [
  623. 'message_type' => 'connect',
  624. 'data' => [
  625. 'user_info' => $res['data']['3'],
  626. 'conversationId' => $conversationId,
  627. ]
  628. ];
  629. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf));
  630. unset($noticeKf);
  631. // 写入接入值
  632. $key = date('Ymd') . 'success_in';
  633. self::$global->$key = 0;
  634. do {
  635. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  636. unset(self::$global->$oldKey);
  637. } while (!self::$global->increment($key));
  638. unset($key);
  639. } else {
  640. $waitMsg = '';
  641. switch ($res['code']) {
  642. case -1:
  643. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  644. break;
  645. case -2:
  646. break;
  647. case -3:
  648. break;
  649. case -4:
  650. $number = count(self::$global->userList);
  651. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  652. break;
  653. }
  654. $waitMessage = [
  655. 'message_type' => 'wait',
  656. 'data' => [
  657. 'content' => $waitMsg,
  658. ]
  659. ];
  660. Gateway::sendToClient($client_id, json_encode($waitMessage));
  661. unset($waitMessage);
  662. }
  663. }
  664. /**
  665. * 给客服分配会员【均分策略】
  666. * @param $kfList
  667. * @param $userList
  668. * @param $group
  669. * @param $total
  670. */
  671. private static function assignmentTask($kfList, $userList, $group, $total)
  672. {
  673. // 没有客服上线
  674. if (empty($kfList) || empty($kfList[$group])) {
  675. return ['code' => -1];
  676. }
  677. // 没有待分配的会员
  678. if (empty($userList)) {
  679. return ['code' => -2];
  680. }
  681. // 未设置每个客服可以服务多少人
  682. if (0 == $total) {
  683. return ['code' => -3];
  684. }
  685. // 查看该组的客服是否在线
  686. if (!isset($kfList[$group])) {
  687. return ['code' => -1];
  688. }
  689. $kf = $kfList[$group];
  690. $user = array_shift($userList);
  691. $kf = array_shift($kf);
  692. $min = $kf['task'];
  693. $flag = $kf['id'];
  694. foreach ($kfList[$group] as $key => $vo) {
  695. if ($vo['task'] < $min) {
  696. $min = $vo['task'];
  697. $flag = $key;
  698. }
  699. }
  700. unset($kf);
  701. // 需要排队了
  702. if ($kfList[$group][$flag]['task'] == $total) {
  703. return ['code' => -4];
  704. }
  705. $kfList[$group][$flag]['task'] += 1;
  706. array_push($kfList[$group][$flag]['user_info'], $user['client_id']); // 被分配的用户信息
  707. return [
  708. 'code' => 1,
  709. 'data' => [
  710. $kfList[$group][$flag]['id'],
  711. $kfList[$group][$flag]['name'],
  712. $kfList[$group][$flag]['client_id'],
  713. $user,
  714. $kfList,
  715. $userList
  716. ]
  717. ];
  718. }
  719. /**
  720. * 获取最大的服务人数
  721. * @return int
  722. */
  723. private static function getMaxServiceNum()
  724. {
  725. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  726. if (!empty($maxNumber)) {
  727. $maxNumber = 5;
  728. } else {
  729. $maxNumber = $maxNumber['0']['max_service'];
  730. }
  731. return $maxNumber;
  732. }
  733. /**
  734. * 将内存中的数据写入统计表
  735. * @param int $flag
  736. */
  737. private static function writeLog($flag = 1)
  738. {
  739. // 上午 8点 到 22 点开始统计
  740. if (date('H') < 8 || date('H') > 22) {
  741. return;
  742. }
  743. // 当前正在接入的人 和 在线客服数
  744. $kfList = self::$global->kfList;
  745. $nowTalking = 0;
  746. $onlineKf = 0;
  747. if (!empty($kfList)) {
  748. foreach ($kfList as $key => $vo) {
  749. $onlineKf += count($vo);
  750. foreach ($vo as $k => $v) {
  751. $nowTalking += count($v['user_info']);
  752. }
  753. }
  754. }
  755. // 在队列中的用户
  756. $inQueue = count(self::$global->userList);
  757. $key = date('Ymd') . 'total_in';
  758. $key2 = date('Ymd') . 'success_in';
  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. 'now_date' => date('Y-m-d')
  766. ];
  767. self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
  768. if (2 == $flag) {
  769. $param = [
  770. 'is_talking' => $nowTalking,
  771. 'in_queue' => $inQueue,
  772. 'online_kf' => $onlineKf,
  773. 'success_in' => self::$global->$key2,
  774. 'total_in' => self::$global->$key,
  775. 'add_date' => date('Y-m-d'),
  776. 'add_hour' => date('H'),
  777. 'add_minute' => date('i'),
  778. ];
  779. self::$db->insert('ws_service_data')->cols($param)->query();
  780. }
  781. unset($kfList, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
  782. }
  783. /**
  784. * 机器人问答
  785. * @param $client_id 服务ID
  786. * @param $message 数据
  787. */
  788. private static function toRobot($client_id, $message)
  789. {
  790. $groups_id = $message['data']['groups_id'];
  791. $robot_name = $message['data']['robot_name'];
  792. $robotgroups_id = $message['data']['robotgroups_id'];
  793. // 查询问题.
  794. $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 . "'");
  795. $chat_message = [
  796. 'message_type' => 'chatMessage',
  797. 'data' => [
  798. 'name' => '智能助手',
  799. 'time' => date('H:i'),
  800. 'content' => $getRobot ? htmlspecialchars($getRobot[0]['robot_content']) : 'error',
  801. ]
  802. ];
  803. Gateway::sendToClient($client_id, json_encode($chat_message));
  804. }
  805. /**
  806. * 评价
  807. * @param $client_id 服务ID
  808. * @param $message 数据
  809. */
  810. private static function evaluate($client_id, $message)
  811. {
  812. // 修改数据库.
  813. $evaluate_id = $message['data']['evaluate_id'];
  814. $result = self::$db->query("UPDATE `ws_service_log` SET `evaluate_id` = '" . $evaluate_id . "' WHERE `client_id`='" . $client_id . "'");
  815. if ($result) {
  816. $chat_message = [
  817. 'message_type' => 'evaluate',
  818. 'data' => [
  819. 'status' => 1,
  820. 'time' => date('H:i'),
  821. ]
  822. ];
  823. } else {
  824. $chat_message = [
  825. 'message_type' => 'evaluate',
  826. 'data' => [
  827. 'status' => 2,
  828. 'time' => date('H:i'),
  829. ]
  830. ];
  831. }
  832. Gateway::sendToClient($client_id, json_encode($chat_message));
  833. }
  834. //踢掉同一用户的旧用户
  835. private static function tickOlduser($uid)
  836. {
  837. }
  838. }