Events.php 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858
  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.200', '3306', 'vali', '1234', '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. self::writeLogKfStatus(0, 0, 0);
  76. // 1分钟统计一次实时数据
  77. Timer::add(60 * 1, function () {
  78. self::writeLog(1);
  79. });
  80. // 40分钟写一次当前日期点数的log数据
  81. Timer::add(60 * 40, function () {
  82. self::writeLog(2);
  83. });
  84. //每1分钟发一次本组排队数
  85. Timer::add(60 * 1, function () {
  86. self::lineup();
  87. });
  88. //初始化.....
  89. self::upsystemconfig();
  90. //每5分钟更新一次系统配置文件
  91. Timer::add(60 * 10, function () {
  92. self::upsystemconfig();
  93. });
  94. // 检查对话时效给出.
  95. Timer::add(6, function () {
  96. self::overTime();
  97. });
  98. // 实时监控.
  99. Timer::add(60, function () {
  100. $adminList = self::$global->adminList ?? [];
  101. self::systemMonitoring($adminList);
  102. });
  103. }
  104. }
  105. /**
  106. * 每分钟定时向客服发送一次排队情况
  107. */
  108. public static function lineup()
  109. {
  110. $userlist = self::$global->userList;
  111. $kflist = self::$global->kfList;
  112. if (empty($userlist) || empty($kflist)) {
  113. return;
  114. }
  115. $return = [];
  116. foreach ($userlist as $val) {
  117. $return[$val['group']] = isset($return[$val['group']]) ? $return[$val['group']] + 1 : 1;
  118. }
  119. $krgroupclientid = [];
  120. foreach ($kflist as $gid => $sval) {
  121. foreach ($sval as $tval) {
  122. $krgroupclientid[$gid][] = $tval['client_id'];
  123. }
  124. }
  125. foreach ($return as $fgroup => $fval) {
  126. foreach ($krgroupclientid as $sikey => $sival) {
  127. if ($fgroup == $sikey) {
  128. Gateway::sendToClient($sival, json_encode(['type' => 'lineupCount', $fval], 256));
  129. }
  130. }
  131. }
  132. return;
  133. }
  134. /**
  135. * 当客户端连接时触发
  136. * 如果业务不需此回调可以删除onConnect
  137. *
  138. * @param int $client_id 连接id
  139. */
  140. public static function onConnect($client_id)
  141. {
  142. // 检测是否开启自动应答
  143. $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 1');
  144. if (!empty($sayHello) && 1 == $sayHello['0']['status']) {
  145. $hello = [
  146. 'message_type' => 'helloMessage',
  147. 'data' => [
  148. 'name' => '智能助手',
  149. 'time' => date('H:i'),
  150. 'content' => $sayHello['0']['word']
  151. ]
  152. ];
  153. Gateway::sendToClient($client_id, json_encode($hello, 256));
  154. unset($hello);
  155. }
  156. unset($sayHello);
  157. // 检测是否开启广告
  158. $advertisement = self::$db->query('select * from `ws_advertisement` where `advertisement_status` = 1');
  159. if (!empty($advertisement)) {
  160. $chat_message = [
  161. 'message_type' => 'advertisement',
  162. 'data' => $advertisement
  163. ];
  164. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  165. unset($chat_message);
  166. }
  167. unset($advertisement);
  168. }
  169. /**
  170. * 当客户端发来消息时触发
  171. * @param int $client_id 连接id
  172. * @param mixed $message 具体消息
  173. */
  174. public static function onMessage($client_id, $message)
  175. {
  176. if ($message == '{"type":"ping"}' || $message == '{"type":"pong"}') {
  177. //Gateway::sendToCurrentClient('{"type":"pong"}');
  178. return;
  179. } else {
  180. echo "onMessage: " . $message . "\r\n";
  181. print_r([self::$global->kfList, self::$global->userList, self::$global->uidSimpleList, self::$global->userToKf]);
  182. }
  183. $message = json_decode($message, true);
  184. if (isset($message['type'])) {
  185. switch ($message['type']) {
  186. // 管理员初始化
  187. case 'adminInit':
  188. $token = $message['token'];
  189. self::adminInit($client_id, $token);
  190. break;
  191. // 客服初始化
  192. case 'init':
  193. $data = $message['data'];
  194. self::Kfinit($client_id, $data);
  195. break;
  196. // 顾客初始化
  197. case 'userInit';
  198. $data = $message['data'];
  199. self::userInitEnt($client_id, $data);
  200. break;
  201. //在线客服信息
  202. case 'getkfonlines':
  203. Gateway::sendToCurrentClient(json_encode(self::getkfonlines(), 256));
  204. break;
  205. case 'chatMessage':
  206. $client = Gateway::getClientIdByUid($message['data']['to_id']);
  207. if (!empty($client)) {
  208. $chat_message = [
  209. 'message_type' => 'chatMessage',
  210. 'data' => [
  211. 'name' => $message['data']['from_name'],
  212. 'id' => $message['data']['from_id'],
  213. 'time' => date('H:i'),
  214. 'content' => $message['data']['content'],
  215. ]
  216. ];
  217. Gateway::sendToClient($client['0'], json_encode($chat_message));
  218. unset($chat_message);
  219. // 聊天信息入库
  220. $serviceLog = [
  221. 'from_id' => $message['data']['from_id'],
  222. 'from_name' => $message['data']['from_name'],
  223. 'to_id' => $message['data']['to_id'],
  224. 'to_name' => $message['data']['to_name'],
  225. 'content' => $message['data']['content'],
  226. 'servicelog_id' => $message['data']['conversationId'],
  227. 'time_line' => time()
  228. ];
  229. self::$db->insert('ws_chat_log')->cols($serviceLog)->query();
  230. /*
  231. if ($message['data']['sensitiveNumber']) {
  232. }
  233. self::$db->query("update `ws_alarm` set `alarm_corresponding` = '$corresponding',alarm_respond=2 where `servicelog_id`= '$servicelog_id'");
  234. */
  235. unset($serviceLog);
  236. }
  237. if (isset($message['data']['isFirst']) && $message['data']['isFirst']) {
  238. $servicelog_id = $message['data']['conversationId'];
  239. $serviceLog = self::$db->query("select `start_time` from `ws_service_log` where `servicelog_id`= '$servicelog_id'");
  240. $corresponding = time() - $serviceLog[0]['start_time'];
  241. self::$db->query("update `ws_alarm` set `alarm_corresponding` = '$corresponding',alarm_respond=2 where `servicelog_id`= '$servicelog_id'");
  242. }
  243. break;
  244. // 转接
  245. case 'changeGroup':
  246. // 通知客户端转接中
  247. $simpleList = self::$global->uidSimpleList;
  248. if (!isset($simpleList[$message['uid']])) { // 客户已经退出
  249. return;
  250. }
  251. $userClient = $simpleList[$message['uid']]['0'];
  252. $userGroup = $simpleList[$message['uid']]['1']; // 会员原来的分组也是客服的分组
  253. $reLink = [
  254. 'message_type' => 'relinkMessage'
  255. ];
  256. Gateway::sendToClient($userClient, json_encode($reLink, 256));
  257. unset($reLink);
  258. // 记录该客服与该会员的服务结束
  259. $servicelog_id = $message['data']['conversationId'];
  260. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `servicelog_id`= '" . $servicelog_id . "'");
  261. // 修改会话时长
  262. $serviceLog = self::$db->query("select `start_time`,`intime` from `ws_service_log` where `servicelog_id`= '$servicelog_id'");
  263. $logCount = self::$db->query("select count(*) as `count` from `ws_chat_log` where `servicelog_id`= '$servicelog_id'");
  264. $alarmCount = $logCount[0]['count'];
  265. $cvtOvertime = time() - $serviceLog[0]['start_time'];
  266. $alarmLineTime = $serviceLog[0]['start_time'] - $serviceLog[0]['intime'];
  267. self::$db->query("update `ws_alarm` set `alarm_cvtOvertime` = '$cvtOvertime',`alarm_lineTime` = '$alarmLineTime',`alarm_count` = '$alarmCount'
  268. where `servicelog_id`= '$servicelog_id'");
  269. // 从当前客服的服务表中删除这个会员
  270. $old = $kfList = self::$global->kfList;
  271. if (!isset($kfList[$userGroup])) {
  272. $waitMsg = '暂时没有相关客服上班,请稍后再咨询。';
  273. // 逐一通知
  274. foreach (self::$global->userList as $vo) {
  275. $waitMessage = [
  276. 'message_type' => 'wait',
  277. 'data' => [
  278. 'content' => $waitMsg,
  279. ]
  280. ];
  281. Gateway::sendToClient($userClient, json_encode($waitMessage, 256));
  282. unset($waitMessage);
  283. }
  284. return;
  285. }
  286. $myList = $kfList[$userGroup]; // 该客服分组数组
  287. foreach ($myList as $key => $vo) {
  288. if (in_array($userClient, $vo['user_info'])) {
  289. // 维护现在的该客服的服务信息
  290. $kfList[$userGroup][$key]['task'] -= 1; // 当前服务的人数 -1
  291. foreach ($vo['user_info'] as $k => $v) {
  292. if ($userClient == $v) {
  293. unset($kfList[$userGroup][$key]['user_info'][$k]);
  294. break;
  295. }
  296. }
  297. break;
  298. }
  299. }
  300. while (!self::$global->cas('kfList', $old, $kfList)) {
  301. }; // 刷新内存中客服的服务列表
  302. unset($old, $kfList, $myList);
  303. // 将会员加入队列中
  304. $userList = self::$global->userList;
  305. do {
  306. $NewUserList = $userList;
  307. $NewUserList[$message['uid']] = [
  308. 'id' => $message['uid'],
  309. 'name' => $message['name'],
  310. 'avatar' => $message['avatar'],
  311. 'ip' => $message['ip'],
  312. 'group' => $message['group'], // 指定要链接的分组
  313. 'client_id' => $userClient
  314. ];
  315. } while (!self::$global->cas('userList', $userList, $NewUserList));
  316. unset($NewUserList, $userList);
  317. // 执行会员分配通知双方
  318. self::userOnlineTask($userClient, $message['group']);
  319. unset($userClient, $userGroup);
  320. break;
  321. case 'closeUser':
  322. $userInfo = self::$global->uidSimpleList;
  323. if (isset($userInfo[$message['uid']])) {
  324. $waitMessage = [
  325. 'message_type' => 'wait',
  326. 'data' => [
  327. 'content' => '暂时没有客服上班,请稍后再咨询。',
  328. ]
  329. ];
  330. Gateway::sendToClient($userInfo[$message['uid']]['0'], json_encode($waitMessage, 256));
  331. unset($waitMessage);
  332. }
  333. unset($userInfo);
  334. break;
  335. // 机器人问答.
  336. case 'toRobot':
  337. self::toRobot($client_id, $message);
  338. break;
  339. // 评价.
  340. case 'evaluate':
  341. self::evaluate($client_id, $message);
  342. break;
  343. // 客服关闭会话.
  344. case 'kfCloseUser':
  345. $userId = $message['data']['to_id'];
  346. $client = Gateway::getClientIdByUid($userId);
  347. if (!empty($client)) {
  348. $clientId = $client['0'];
  349. self::serverClose($clientId, $message['data']['conversationId']);
  350. }
  351. break;
  352. // 客服更改状态.
  353. case 'kfOnline':
  354. $kfList = self::$global->kfList;
  355. $userId = $message['data']['uid'];
  356. $status = $message['data']['status'];
  357. foreach ($kfList as $k => $v) {
  358. foreach ($v as $ke => $va) {
  359. if ($ke == $userId) {
  360. $kfList[$k][$ke]['status'] = $status;
  361. }
  362. }
  363. }
  364. self::$global->kfList = $kfList;
  365. self::writeLogKfStatus($userId, $status);
  366. break;
  367. case 'changeOtherhKeFu';
  368. self::changeOtherhKeFu($client_id, $message);
  369. break;
  370. // 弹出评价.
  371. case 'getEvaluate';
  372. $client = Gateway::getClientIdByUid($message['data']['to_id']);
  373. if (!empty($client)) {
  374. $chat_message = [
  375. 'message_type' => 'getEvaluate',
  376. 'data' => [
  377. 'content' => '欢迎你的咨询,请对我们的服务做出评价',
  378. ]
  379. ];
  380. Gateway::sendToClient($client['0'], json_encode($chat_message, 256));
  381. unset($chat_message);
  382. }
  383. }
  384. }
  385. }
  386. //获取在线客服列表
  387. public static function getkfonlines()
  388. {
  389. $return = [
  390. 'message_type' => 'onlinekfs',
  391. 'data' => [],
  392. ];
  393. $nowkfid = $_SESSION['uid'];
  394. $kfs = self::$global->kfList;
  395. $groupnamemap = self::$global->groupmap;
  396. if (!$kfs || empty($nowkfid)) {
  397. return $return;
  398. }
  399. $ret = [];
  400. foreach ($kfs as $gruop => $users) {
  401. foreach ($users as $uid => $uinfo) {
  402. if ($uid != $nowkfid) {
  403. $ret[] = ['groupid' => $gruop, 'groupname' => $groupnamemap[$gruop], 'kfuid' => $uid, 'kfname' => $uinfo['name'], 'kfjobname' => $uinfo['job_name']];
  404. }
  405. }
  406. }
  407. $return['data'] = $ret;
  408. return $return;
  409. }
  410. //客户工单内部组转接
  411. public static function changeOtherhKeFu($client_id, $smessage)
  412. {
  413. $message = $smessage['data'];
  414. $groupid = isset($message['group']) ? intval($message['group']) : 0;
  415. $toukfid = isset($message['toukfuid']) ? $message['toukfuid'] : 0;
  416. $fromkfuid = isset($message['fromkfuid']) ? $message['fromkfuid'] : 0;
  417. $uid = isset($message['uid']) ? $message['uid'] : 0;
  418. $word = isset($message['word']) ? $message['word'] : '';
  419. if (empty($groupid) || empty($toukfid) || empty($fromkfuid) || empty($uid) || empty($word) || ($toukfid == $fromkfuid)) {
  420. return false;
  421. }
  422. if (!Gateway::isUidOnline($toukfid) || !Gateway::isUidOnline($uid)) {
  423. return false;
  424. }
  425. $tokfidclientid = Gateway::getClientIdByUid($toukfid);
  426. $tokfidclientid = $tokfidclientid['0'];
  427. $uidclientid = Gateway::getClientIdByUid($uid);
  428. $uidclientid = $uidclientid['0'];
  429. $kfList = $kfList_new = self::$global->kfList;
  430. $userToKf = $userToKf_new = self::$global->userToKf;
  431. if (!isset($kfList[$groupid]) || !isset($kfList[$groupid][$toukfid]) || !isset($kfList[$groupid][$fromkfuid])) {
  432. return false;
  433. }
  434. if ($kfList[$groupid][$toukfid]['status'] != 1) {
  435. return false;
  436. }
  437. foreach ($kfList[$groupid] as $key => $val) {
  438. if ($key == $fromkfuid) {
  439. $kfList_new[$groupid][$fromkfuid]['task']--;
  440. foreach ($kfList[$groupid][$key]['user_info'] as $skey => $sval) {
  441. if ($sval == $uidclientid) {
  442. unset($kfList_new[$groupid][$key]['user_info'][$skey]);
  443. }
  444. }
  445. }
  446. if ($key == $toukfid) {
  447. $kfList_new[$groupid][$toukfid]['task']++;
  448. array_push($kfList_new[$groupid][$key]['user_info'], $uidclientid);
  449. }
  450. }
  451. do {
  452. } while (!self::$global->cas('kfList', $kfList, $kfList_new));
  453. if (isset($userToKf[$uid])) {
  454. $userToKf_new[$uid]['1'] = $toukfid;
  455. }
  456. do {
  457. } while (!self::$global->cas('userToKf', $userToKf, $userToKf_new));
  458. /////////取消原有会话,开启新会话
  459. $histarttimelimit = time() - 3600 * 24;
  460. $bindval = ['user_id' => $uid, 'client_id' => $uidclientid, 'kf_id' => intval(trim($fromkfuid, 'KF')), 'histime' => $histarttimelimit];
  461. $oldlog = self::$db->select('*')->from('ws_service_log')->where('user_id= :user_id and client_id=:client_id and kf_id=:kf_id and status!=2 and start_time>=:histime ')->bindValues($bindval)->row();
  462. if (!$oldlog) {
  463. return false;
  464. }
  465. self::$db->update('ws_service_log')->cols(['status' => 2, 'end_time' => time()])->where('servicelog_id=' . $oldlog['servicelog_id'])->query();
  466. unset($oldlog['servicelog_id']);
  467. // 修改会话时长
  468. $servicelog_id = $oldlog['servicelog_id'];
  469. $serviceLog = self::$db->query("select `start_time`,`intime` from `ws_service_log` where `servicelog_id`= '$servicelog_id'");
  470. $logCount = self::$db->query("select count(*) as `count` from `ws_chat_log` where `servicelog_id`= '$servicelog_id'");
  471. $alarmCount = $logCount[0]['count'];
  472. $cvtOvertime = time() - $serviceLog[0]['start_time'];
  473. $alarmLineTime = $serviceLog[0]['start_time'] - $serviceLog[0]['intime'];
  474. self::$db->query("update `ws_alarm` set `alarm_cvtOvertime` = '$cvtOvertime',`alarm_lineTime` = '$alarmLineTime',`alarm_count` = '$alarmCount'
  475. where `servicelog_id`= '$servicelog_id'");
  476. $oldlog = array_merge($oldlog, ['kf_id' => intval(trim($toukfid, 'KF')), 'start_time' => time(), 'end_time' => 0, 'status' => 1, 'evaluate_id' => 0]);
  477. $new_id = self::$db->insert('ws_service_log')->cols($oldlog)->query();
  478. if (!$new_id) {
  479. return false;
  480. }
  481. ///通知消息发送--------------
  482. // 通知会员发送信息绑定客服的id
  483. $noticeUser = [
  484. 'message_type' => 'connect',
  485. 'data' => [
  486. 'kf_id' => $toukfid,
  487. 'conversationId' => $new_id,
  488. 'kf_name' => Gateway::getSession(Gateway::getClientIdByUid($toukfid)['0'])['name'],
  489. 'serverInfo' => self::$global->kfList[$groupid][$toukfid],
  490. ]
  491. ];
  492. Gateway::sendToClient($uidclientid, json_encode($noticeUser, 256));
  493. unset($noticeUser);
  494. // 通知客服端绑定会员的信息
  495. $noticeKf = [
  496. 'message_type' => 'connect',
  497. 'data' => [
  498. 'user_info' => $uid,
  499. 'conversationId' => $new_id,
  500. ]
  501. ];
  502. Gateway::sendToClient($tokfidclientid, json_encode($noticeKf, 256));
  503. unset($noticeKf);
  504. self::servicetrutoother('OUT', $fromkfuid, $toukfid, $oldlog['servicelog_id'], $uid);
  505. self::servicetrutoother('IN', $toukfid, $fromkfuid, $new_id, $uid);
  506. //回转接人,转接成功
  507. Gateway::sendToCurrentClient(json_encode(['message_type' => 'trunconnect', 'data' => ['status' => 1], 256]));
  508. return;
  509. }
  510. //客服接入sock,及初始化
  511. public static function Kfinit($client_id, $message)
  512. {
  513. $kfList = self::$global->kfList;
  514. //客服登陆验证 不符合的直接断掉
  515. //$logcheck = true; //开发时使用
  516. $kfinfo = self::KfloginChedk($client_id, $message);
  517. if (empty($kfinfo)) {
  518. Gateway::sendToClient($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "验证失败"], 256));
  519. Gateway::closeCurrentClient();
  520. return true;
  521. } elseif ($kfinfo['status'] != 1) {
  522. Gateway::sendToClient($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "禁用中..."], 256));
  523. Gateway::closeCurrentClient();
  524. return true;
  525. }
  526. if (isset($kfList[$message['group']][$message['uid']])) {
  527. Gateway::sendToCurrentClient(json_encode(['message_type' => 'reLoginErr', 'msg' => '你的账号已经登陆过,请先退出再登陆'], 256));
  528. Gateway::closeCurrentClient();
  529. return;
  530. }
  531. // 如果该客服未在内存中记录则记录
  532. if (!isset($kfList[$message['group']]) || !array_key_exists($message['uid'], $kfList[$message['group']])) {
  533. do {
  534. $newKfList = $kfList;
  535. $newKfList[$message['group']][$message['uid']] = [
  536. 'id' => 'KF' . $kfinfo['id'],
  537. 'name' => $kfinfo['user_name'],
  538. 'job_name' => $kfinfo['user_job_number'],
  539. 'avatar' => $kfinfo['user_avatar'],
  540. 'client_id' => $client_id,
  541. 'task' => 0,
  542. 'signature' => $kfinfo['signature'],
  543. 'status' => 2,// 1为在线(接收分配、接收消息)2为隐身(不接收分配、只接收消息)3、休息
  544. 'user_info' => []
  545. ];
  546. } while (!self::$global->cas('kfList', $kfList, $newKfList));
  547. unset($newKfList, $kfList);
  548. } else if (isset($kfList[$message['group']][$message['uid']])) {
  549. do {
  550. $newKfList = $kfList;
  551. $newKfList[$message['group']][$message['uid']]['client_id'] = $client_id;
  552. } while (!self::$global->cas('kfList', $kfList, $newKfList));
  553. unset($newKfList, $kfList);
  554. }
  555. // 绑定 client_id 和 uid
  556. Gateway::bindUid($client_id, $message['uid']);
  557. $_SESSION['group'] = $message['group'];
  558. $_SESSION['iskefu'] = 1;
  559. $_SESSION['uid'] = $message['uid'];
  560. $_SESSION['name'] = $message['name'];
  561. Gateway::joinGroup($client_id, 'group_' . $message['group']);
  562. $chat_message = [
  563. 'message_type' => 'loginSuccess',
  564. ];
  565. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  566. unset($chat_message);
  567. self::writeLogKfStatus($message['uid'], 2);
  568. // TODO 尝试拉取用户来服务 [二期规划]
  569. }
  570. /**
  571. * 管理员
  572. * @param $client_id 服务ID
  573. * @param $message 数据
  574. */
  575. public static function adminInit($client_id, $token)
  576. {
  577. // 查询token是否存在.
  578. $systemConfigData = self::$db->query("SELECT `id` FROM `ws_admins` where `token`= '$token'");
  579. //print_r(self::$global->adminList);
  580. if ($systemConfigData) {
  581. $adminList = self::$global->adminList;
  582. $adminList[] = $client_id;
  583. self::$global->adminList = $adminList;
  584. self::systemMonitoring([$client_id]);
  585. } else {
  586. Gateway::closeClient($client_id);
  587. }
  588. }
  589. //客服登陆验证
  590. public static function KfloginChedk($client, $messageArray)
  591. {
  592. $uid = isset($messageArray['uid']) ? $messageArray['uid'] : '';
  593. $token = isset($messageArray['token']) ? $messageArray['token'] : '';
  594. if (empty($uid) || empty($token)) {
  595. return false;
  596. }
  597. $expire_time_vali = time() - 60 * 60 * 24;
  598. $kfid = intval(substr($uid, 2));
  599. $ret = self::$db->select('*')->from('ws_users')->where('id=:id and token=:token and expire_time>=:expire_time')->bindValues(array('id' => $kfid, 'token' => $token, 'expire_time' => $expire_time_vali))->row();
  600. if ($ret) {
  601. self::$db->update('ws_users')->cols(array('online_status' => 1, 'online_connectid' => $client))->where('id=' . $kfid)->query();
  602. return $ret;
  603. }
  604. return false;
  605. }
  606. //用户发送邦定用户事件
  607. public static function userInitEnt($client_id, $message)
  608. {
  609. $userList = self::$global->userList;
  610. // 如果该顾客未在内存中记录则记录
  611. $uidSimpleList = self::$global->uidSimpleList;
  612. if (isset($uidSimpleList[$message['uid']])) {
  613. $uidSimpleList = self::$global->uidSimpleList;
  614. $oldclientid = $uidSimpleList[$message['uid']]['0'];
  615. Gateway::sendToClient($oldclientid, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆,本次退出'], 256));
  616. Gateway::closeClient($oldclientid);
  617. sleep(2);
  618. }
  619. $group = $message['group'];
  620. $onlinekf = self::$global->kfList;
  621. if (!isset($onlinekf[$group]) || count($onlinekf[$group]) <= 0) {
  622. Gateway::sendToClient($client_id, json_encode(['message_type' => 'notice', 'content' => '暂时没有客服上班,请稍后再咨询。'], 256));
  623. sleep(1);
  624. Gateway::closeClient($client_id);
  625. return;
  626. }
  627. if (!array_key_exists($message['uid'], $userList)) {
  628. do {
  629. $NewUserList = $userList;
  630. $NewUserList[$message['uid']] = [
  631. 'id' => $message['uid'],
  632. 'name' => $message['name'],
  633. 'avatar' => $message['avatar'],
  634. 'website' => $_SESSION['origin'],//$_SERVER['HTTP_ORIGIN'],
  635. 'browse' => Gateway::browse_info(),
  636. 'system' => Gateway::get_os(),
  637. 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
  638. 'group' => $message['group'],
  639. 'intime' => time(),
  640. 'client_id' => $client_id
  641. ];
  642. } while (!self::$global->cas('userList', $userList, $NewUserList));
  643. unset($NewUserList, $userList);
  644. // 维护 UID对应的client_id 数组
  645. do {
  646. $old = $newList = self::$global->uidSimpleList;
  647. $newList[$message['uid']] = [
  648. $client_id,
  649. $message['group']
  650. ];
  651. } while (!self::$global->cas('uidSimpleList', $old, $newList));
  652. unset($old, $newList);
  653. // 写入接入值
  654. $key = date('Ymd') . 'total_in';
  655. self::$global->$key = 0;
  656. do {
  657. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  658. unset(self::$global->$oldKey);
  659. } while (!self::$global->increment($key));
  660. unset($key);
  661. }
  662. // 绑定 client_id 和 uid
  663. Gateway::bindUid($client_id, $message['uid']);
  664. $_SESSION['iskefu'] = 0;
  665. $_SESSION['uid'] = $message['uid'];
  666. // 尝试分配新会员进入服务
  667. self::userOnlineTask($client_id, $message['group'], $message['uid']);
  668. }
  669. /**
  670. * 当用户断开连接时触发
  671. * @param int $client_id 连接id
  672. *
  673. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  674. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  675. */
  676. public static function onClose($client_id)
  677. {
  678. $isKefuoff = isset($_SESSION['iskefu']) ? $_SESSION['iskefu'] : 0;
  679. $uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : false;
  680. //echo "下线:$uid - $client_id - $isKefuoff \n";
  681. $adminList = self::$global->adminList ?? [];
  682. $key = array_search($client_id, $adminList);
  683. if (strlen($key)) {
  684. array_splice($adminList, $key, 1);
  685. self::$global->adminList = $adminList;
  686. }
  687. if (empty($uid)) {
  688. return;
  689. }
  690. if ($isKefuoff) {
  691. self::serviceOffline($client_id, $uid);
  692. } else {
  693. self::guestOffline($client_id, $uid);
  694. }
  695. return;
  696. }
  697. //客服下线了
  698. public static function serviceOffline($client_id, $uid)
  699. {
  700. $group = $_SESSION['group'];
  701. $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
  702. $user_info = $kefuinfo_old_new[$group][$uid]['user_info'];
  703. $simpliUsers = self::$global->uidSimpleList;
  704. $simpliUsersID_UID_Arr = [];
  705. if (!empty($simpliUsers)) {
  706. foreach ($simpliUsers as $key => $val) {
  707. $simpliUsersID_UID_Arr[$val['0']] = $key;
  708. }
  709. }
  710. $now = time();
  711. if (!empty($user_info)) {
  712. foreach ($user_info as $val) {
  713. Gateway::sendToClient($val, json_encode(['type' => 'serviceoffline', 'msg' => '客户人员下线!'], 256));
  714. if (isset($simpliUsersID_UID_Arr[$val])) {
  715. self::$db->query("update `ws_service_log` set `status` = '2',end_time=$now where `user_id`= '$simpliUsersID_UID_Arr[$val]' and kf_id='$uid' and group_id=$group and `status`!=2 ");
  716. // 修改会话时长
  717. $serviceLog = self::$db->query("select `start_time`,`servicelog_id`,`intime` from `ws_service_log` where `user_id`= '$simpliUsersID_UID_Arr[$val]' and kf_id='$uid' and group_id=$group and `status`!=2");
  718. $logCount = self::$db->query("select count(*) as `count` from `ws_chat_log` where `servicelog_id`= '$servicelog_id'");
  719. $alarmCount = $logCount[0]['count'];
  720. $servicelog_id = $serviceLog[0]['servicelog_id'];
  721. $cvtOvertime = time() - $serviceLog[0]['start_time'];
  722. $alarmLineTime = $serviceLog[0]['start_time'] - $serviceLog[0]['intime'];
  723. self::$db->query("update `ws_alarm` set `alarm_cvtOvertime` = '$cvtOvertime',`alarm_lineTime` = '$alarmLineTime',`alarm_count` = '$alarmCount'
  724. where `servicelog_id`= '$servicelog_id'");
  725. }
  726. Gateway::closeClient($val);
  727. }
  728. }
  729. unset($kefuinfo_old_new[$group][$uid]);
  730. $kfid = intval(substr($uid, 2));
  731. self::$db->update('ws_users')->cols(array('online_status' => 0, 'online_connectid' => ''))->where('id=' . $kfid)->query();
  732. do {
  733. } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
  734. self::writeLogKfStatus($uid, 0);
  735. return;
  736. }
  737. //用户下线了
  738. public static function guestOffline($client_id, $uid)
  739. {
  740. $kfuid = -1;
  741. $krclient_id = 0;
  742. $kfgroup = -1;
  743. $userToKf = $userToKfNew = self::$global->userToKf;
  744. if (isset($userToKfNew[$uid])) {
  745. $kfuid = isset($userToKfNew[$uid]['1']) ? $userToKfNew[$uid]['1'] : -1;
  746. $krclient_id = isset(Gateway::getClientIdByUid($kfuid)['0']) ? Gateway::getClientIdByUid($kfuid)['0'] : 0;
  747. unset($userToKfNew[$uid]);
  748. do {
  749. } while (!self::$global->cas('userToKf', $userToKf, $userToKfNew));
  750. }
  751. $uidSimpleList = $uidSimpleListNew = self::$global->uidSimpleList;
  752. if (isset($uidSimpleListNew[$uid])) {
  753. $kfgroup = $uidSimpleListNew[$uid]['1'];
  754. unset($uidSimpleListNew[$uid]);
  755. do {
  756. } while (!self::$global->cas('uidSimpleList', $uidSimpleList, $uidSimpleListNew));
  757. }
  758. $userList = $userListNew = self::$global->userList;
  759. $group_wait_count = 0;
  760. if (!empty($userList)) {
  761. $ischange = 0;
  762. foreach ($userList as $key => $val) {
  763. if ($val['group'] == $kfuid) {
  764. $group_wait_count++;
  765. }
  766. if ($val['id'] == $uid) {
  767. unset($userListNew[$key]);
  768. $ischange = 1;
  769. $group_wait_count--;
  770. break;
  771. }
  772. }
  773. if ($ischange) {
  774. do {
  775. } while (!self::$global->cas('userList', $userList, $userListNew));
  776. Gateway::sendToGroup('group_' . $kfgroup, json_encode(['message_type' => 'kfqueuelength', 'leng' => $group_wait_count], 256));
  777. }
  778. }
  779. if ($kfuid != -1 && $kfgroup != -1) {
  780. $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
  781. $ischange_kf_list = 0;
  782. if (isset($kefuinfo_old[$kfgroup][$kfuid])) {
  783. $infos = $kefuinfo_old[$kfgroup][$kfuid]['user_info'];
  784. if ($infos) {
  785. if (is_array($infos)) {
  786. foreach ($infos as $key => $val) {
  787. if ($val == $client_id) {
  788. $ischange_kf_list = 1;
  789. unset($kefuinfo_old_new[$kfgroup][$kfuid]['user_info'][$key]);
  790. $kefuinfo_old_new[$kfgroup][$kfuid]['task'] = $kefuinfo_old_new[$kfgroup][$kfuid]['task'] - 1;
  791. }
  792. }
  793. }
  794. if ($ischange_kf_list) {
  795. do {
  796. } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
  797. $chat_message = [
  798. 'message_type' => 'userClose',
  799. 'data' => [
  800. 'content' => '用户连接已断开',
  801. 'id' => $uid,
  802. 'time' => date('H:i'),
  803. ]
  804. ];
  805. $now = time();
  806. $kf__uid = substr($kfuid, 2);
  807. $sql = "update `ws_service_log` set `status` = '3',end_time=$now where `user_id`= '$uid' and kf_id='$kf__uid' and group_id=$kfgroup and status=1 ";
  808. //echo "客户退出:". $sql ."\n";
  809. self::$db->query($sql);
  810. Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
  811. }
  812. }
  813. }
  814. }
  815. }
  816. /**
  817. * 客服结束会话
  818. * @param int $client_id 连接id
  819. *
  820. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  821. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  822. */
  823. public static function serverClose($client_id, $servicelog_id)
  824. {
  825. // 返回.
  826. $chat_message = [
  827. 'message_type' => 'closeBysever',
  828. 'data' => [
  829. 'content' => '客服停止了该会话',
  830. 'time' => date('H:i'),
  831. ]
  832. ];
  833. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  834. Gateway::closeClient($client_id);
  835. $now = time();
  836. $sql = "update `ws_service_log` set `status`='2',end_time=$now where `servicelog_id`= '$servicelog_id'";
  837. //echo "客户退出:". $sql ."\n";
  838. self::$db->query($sql);
  839. $isServiceUserOut = false;
  840. // 修改会话时长
  841. $serviceLog = self::$db->query("select `start_time`,`intime` from `ws_service_log` where `servicelog_id`= '$servicelog_id'");
  842. $logCount = self::$db->query("select count(*) as `count` from `ws_chat_log` where `servicelog_id`= '$servicelog_id'");
  843. $alarmCount = $logCount[0]['count'];
  844. $cvtOvertime = time() - $serviceLog[0]['start_time'];
  845. $alarmLineTime = $serviceLog[0]['start_time'] - $serviceLog[0]['intime'];
  846. self::$db->query("update `ws_alarm` set `alarm_cvtOvertime` = '$cvtOvertime',`alarm_lineTime` = '$alarmLineTime',`alarm_count` = '$alarmCount'
  847. where `servicelog_id`= '$servicelog_id'");
  848. // 将会员服务信息,从客服的服务列表中移除
  849. $old = $kfList = self::$global->kfList;
  850. foreach ($kfList as $k => $v) {
  851. foreach ($v as $key => $vo) {
  852. if (in_array($client_id, $vo['user_info'])) {
  853. $isServiceUserOut = true;
  854. // 根据client id 去更新会话工单一些信息
  855. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $client_id . "'");
  856. // 从会员的内存表中检索出该会员的信息,并更新内存
  857. $oldSimple = $simpleList = self::$global->uidSimpleList;
  858. $outUser = [];
  859. foreach ($simpleList as $u => $c) {
  860. if ($c['0'] == $client_id) {
  861. $outUser[] = [
  862. 'user_id' => $u,
  863. 'group_id' => $c['1']
  864. ];
  865. unset($simpleList[$u]);
  866. break;
  867. }
  868. }
  869. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  870. };
  871. unset($oldSimple, $simpleList);
  872. $outUser = self::$db->query("select `user_id`,`group_id` from `ws_service_log` where `client_id`= '" . $client_id . "'");
  873. // 通知 客服删除退出的用户
  874. if (!empty($outUser)) {
  875. $del_message = [
  876. 'message_type' => 'delUser',
  877. 'data' => [
  878. 'id' => $outUser['0']['user_id']
  879. ]
  880. ];
  881. Gateway::sendToClient($vo['client_id'], json_encode($del_message, 256));
  882. unset($del_message);
  883. // 尝试分配新会员进入服务
  884. self::userOfflineTask($outUser['0']['group_id']);
  885. }
  886. unset($outUser);
  887. // 维护现在的该客服的服务信息
  888. $kfList[$k][$key]['task'] -= 1; // 当前服务的人数 -1
  889. foreach ($vo['user_info'] as $m => $l) {
  890. if ($client_id == $l) {
  891. unset($kfList[$k][$key]['user_info'][$m]);
  892. break;
  893. }
  894. }
  895. // 刷新内存中客服的服务列表
  896. while (!self::$global->cas('kfList', $old, $kfList)) {
  897. };
  898. unset($old, $kfList);
  899. break;
  900. }
  901. }
  902. if ($isServiceUserOut) break;
  903. }
  904. // 尝试从排队的用户中删除退出的客户端
  905. if (false == $isServiceUserOut) {
  906. $old = $userList = self::$global->userList;
  907. foreach (self::$global->userList as $key => $vo) {
  908. if ($client_id == $vo['client_id']) {
  909. $isServiceUserOut = true;
  910. unset($userList[$key]);
  911. break;
  912. }
  913. }
  914. while (!self::$global->cas('userList', $old, $userList)) {
  915. };
  916. // 从会员的内存表中检索出该会员的信息,并更新内存
  917. $oldSimple = $simpleList = self::$global->uidSimpleList;
  918. foreach ($simpleList as $u => $c) {
  919. if ($c['0'] == $client_id) {
  920. unset($simpleList[$u]);
  921. break;
  922. }
  923. }
  924. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  925. };
  926. unset($oldSimple, $simpleList);
  927. }
  928. // 尝试是否是客服退出
  929. if (false == $isServiceUserOut) {
  930. $old = $kfList = self::$global->kfList;
  931. foreach (self::$global->kfList as $k => $v) {
  932. foreach ($v as $key => $vo) {
  933. // 客服服务列表中无数据,才去删除客服内存信息
  934. if ($client_id == $vo['client_id'] && (0 == count($vo['user_info']))) {
  935. unset($kfList[$k][$key]);
  936. break;
  937. }
  938. }
  939. }
  940. while (!self::$global->cas('kfList', $old, $kfList)) {
  941. };
  942. }
  943. }
  944. /**
  945. * 有人退出
  946. * @param $group
  947. */
  948. private static function userOfflineTask($group)
  949. {
  950. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  951. $maxNumber = self::getMaxServiceNum();
  952. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
  953. unset($maxNumber);
  954. if (1 == $res['code']) {
  955. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  956. }; // 更新客服数据
  957. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  958. }; // 更新会员数据
  959. // 服务信息入库
  960. $serviceLog = [
  961. 'user_id' => $res['data']['3']['id'],
  962. 'client_id' => $res['data']['3']['client_id'],
  963. 'user_name' => $res['data']['3']['name'],
  964. 'user_ip' => $res['data']['3']['ip'],
  965. 'user_avatar' => $res['data']['3']['avatar'],
  966. 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
  967. 'start_time' => time(),
  968. 'group_id' => $group,
  969. 'website' => $res['data']['3']['website'],
  970. 'system' => $res['data']['3']['system'],
  971. 'browse' => $res['data']['3']['browse'],
  972. 'status' => 1,
  973. 'intime' => $res['data']['3']['intime'],
  974. 'end_time' => 0
  975. ];
  976. $hisSession = self::$db->select('*')->from('ws_service_log')->where('user_id=:user_id and kf_id=:kf_id and group_id=:group_id and status in (1,3)')->bindValues(array('user_id' => $res['data']['3']['id'], 'kf_id' => intval(ltrim($res['data']['0'], 'KF')), 'group_id' => $group))->row();
  977. if (!$hisSession) {
  978. $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
  979. } else {
  980. self::$db->update('ws_service_log')->cols(['status' => 1])->where('servicelog_id=' . $hisSession['servicelog_id'])->query();
  981. $conversationId = $hisSession['servicelog_id'];
  982. }
  983. unset($serviceLog);
  984. // 通知会员发送信息绑定客服的id
  985. $noticeUser = [
  986. 'message_type' => 'connect',
  987. 'data' => [
  988. 'kf_id' => $res['data']['0'],
  989. 'kf_name' => $res['data']['1'],
  990. 'conversationId' => $conversationId,
  991. 'serverInfo' => self::$global->kfList[$group][$res['data']['0']],
  992. ]
  993. ];
  994. Gateway::sendToClient($res['data']['3']['client_id'], json_encode($noticeUser, 256));
  995. unset($noticeUser);
  996. // 通知客服端绑定会员的信息
  997. $noticeKf = [
  998. 'message_type' => 'connect',
  999. 'data' => [
  1000. 'user_info' => $res['data']['3'],
  1001. 'conversationId' => $conversationId,
  1002. ]
  1003. ];
  1004. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  1005. unset($noticeKf);
  1006. // 逐一通知
  1007. $number = 1;
  1008. foreach (self::$global->userList as $vo) {
  1009. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  1010. $waitMessage = [
  1011. 'message_type' => 'wait',
  1012. 'data' => [
  1013. 'content' => $waitMsg,
  1014. ]
  1015. ];
  1016. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  1017. $number++;
  1018. }
  1019. unset($waitMessage, $number);
  1020. // 写入接入值
  1021. $key = date('Ymd') . 'success_in';
  1022. self::$global->$key = 0;
  1023. do {
  1024. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1025. unset(self::$global->$oldKey);
  1026. } while (!self::$global->increment($key));
  1027. unset($key);
  1028. } else {
  1029. switch ($res['code']) {
  1030. case -1:
  1031. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  1032. // 逐一通知
  1033. foreach (self::$global->userList as $vo) {
  1034. $waitMessage = [
  1035. 'message_type' => 'wait',
  1036. 'data' => [
  1037. 'content' => $waitMsg,
  1038. ]
  1039. ];
  1040. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  1041. }
  1042. break;
  1043. case -2:
  1044. break;
  1045. case -3:
  1046. break;
  1047. case -4:
  1048. // 逐一通知
  1049. $number = 1;
  1050. foreach (self::$global->userList as $vo) {
  1051. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  1052. $waitMessage = [
  1053. 'message_type' => 'wait',
  1054. 'data' => [
  1055. 'content' => $waitMsg,
  1056. ]
  1057. ];
  1058. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  1059. $number++;
  1060. }
  1061. break;
  1062. }
  1063. unset($waitMessage, $number);
  1064. }
  1065. }
  1066. /**
  1067. * 有人进入执行分配
  1068. * @param $client_id
  1069. * @param $group
  1070. * @param $uid
  1071. */
  1072. private static function userOnlineTask($client_id, $group, $uid = 0)
  1073. {
  1074. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  1075. $maxNumber = self::getMaxServiceNum();
  1076. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber, $uid);
  1077. unset($maxNumber);
  1078. if (1 == $res['code']) {
  1079. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  1080. }; // 更新客服数据
  1081. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  1082. }; // 更新会员数据
  1083. $userToKf = self::$global->userToKf;
  1084. $userToKf[$res['data']['3']['id']] = [
  1085. $res['data']['3']['id'],
  1086. $res['data']['0']
  1087. ];
  1088. self::$global->userToKf = $userToKf;
  1089. // 服务信息入库
  1090. $serviceLog = [
  1091. 'user_id' => $res['data']['3']['id'],
  1092. 'client_id' => $res['data']['3']['client_id'],
  1093. 'user_name' => $res['data']['3']['name'],
  1094. 'user_ip' => $res['data']['3']['ip'],
  1095. 'user_avatar' => $res['data']['3']['avatar'],
  1096. 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
  1097. 'start_time' => time(),
  1098. 'group_id' => $group,
  1099. 'website' => $res['data']['3']['website'],
  1100. 'system' => $res['data']['3']['system'],
  1101. 'browse' => $res['data']['3']['browse'],
  1102. 'status' => 1,
  1103. 'intime' => $res['data']['3']['intime'],
  1104. 'end_time' => 0
  1105. ];
  1106. $hisSession = self::$db->select('*')->from('ws_service_log')->where('user_id=:user_id and kf_id=:kf_id and group_id=:group_id and status in (1,3)')->bindValues(array('user_id' => $res['data']['3']['id'], 'kf_id' => intval(ltrim($res['data']['0'], 'KF')), 'group_id' => $group))->row();
  1107. if (!$hisSession) {
  1108. $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
  1109. $alarmData = [
  1110. 'servicelog_id' => $conversationId,
  1111. ];
  1112. self::$db->insert('ws_alarm')->cols($alarmData)->query();
  1113. } else {
  1114. self::$db->update('ws_service_log')->cols(['status' => 1])->where('servicelog_id=' . $hisSession['servicelog_id'])->query();
  1115. $conversationId = $hisSession['servicelog_id'];
  1116. }
  1117. unset($serviceLog);
  1118. // 通知会员发送信息绑定客服的id
  1119. $noticeUser = [
  1120. 'message_type' => 'connect',
  1121. 'data' => [
  1122. 'kf_id' => $res['data']['0'],
  1123. 'conversationId' => $conversationId,
  1124. 'serverInfo' => self::$global->kfList[$group][$res['data']['0']],
  1125. 'kf_name' => $res['data']['1']
  1126. ]
  1127. ];
  1128. Gateway::sendToClient($client_id, json_encode($noticeUser, 256));
  1129. unset($noticeUser);
  1130. // 发送客服欢迎语
  1131. $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 2');
  1132. if (!empty($sayHello) && 1 == $sayHello['0']['status']) {
  1133. $chat_message = [
  1134. 'message_type' => 'chatMessage',
  1135. 'data' => [
  1136. 'name' => $res['data']['1'],
  1137. //'avatar' => self::$global->kfList[$group][$res['data']['0']],
  1138. 'id' => $res['data']['0'],
  1139. 'time' => date('H:i'),
  1140. 'content' => $sayHello['0']['word']
  1141. ]
  1142. ];
  1143. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1144. unset($chat_message);
  1145. }
  1146. unset($sayHello);
  1147. // 通知客服端绑定会员的信息
  1148. $noticeKf = [
  1149. 'message_type' => 'connect',
  1150. 'data' => [
  1151. 'user_info' => $res['data']['3'],
  1152. 'conversationId' => $conversationId,
  1153. ]
  1154. ];
  1155. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  1156. unset($noticeKf);
  1157. // 写入接入值
  1158. $key = date('Ymd') . 'success_in';
  1159. self::$global->$key = 0;
  1160. do {
  1161. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1162. unset(self::$global->$oldKey);
  1163. } while (!self::$global->increment($key));
  1164. unset($key);
  1165. } else {
  1166. $waitMsg = '';
  1167. switch ($res['code']) {
  1168. case -1:
  1169. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  1170. Gateway::sendToClient($client_id, json_encode(['message_type' => "noservice", 'data' => ['content' => $waitMsg]], 256));
  1171. Gateway::closeClient($client_id);
  1172. return;
  1173. break;
  1174. case -2:
  1175. break;
  1176. case -3:
  1177. break;
  1178. case -4:
  1179. $number = count(self::$global->userList);
  1180. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  1181. break;
  1182. }
  1183. $waitMessage = [
  1184. 'message_type' => 'wait',
  1185. 'data' => [
  1186. 'content' => $waitMsg,
  1187. ]
  1188. ];
  1189. Gateway::sendToClient($client_id, json_encode($waitMessage, 256));
  1190. unset($waitMessage);
  1191. }
  1192. $userlist = self::$global->userList;
  1193. $waitcount = 0;
  1194. if ($userlist) {
  1195. foreach ($userlist as $val) {
  1196. if ($val['group'] == $group) {
  1197. $waitcount++;
  1198. }
  1199. }
  1200. Gateway::sendToGroup('group_' . $group, json_encode(['message_type' => 'kfqueuelength', 'leng' => $waitcount], 256));
  1201. self::todayqueuelength();
  1202. }
  1203. }
  1204. //今天排序累加
  1205. private static function todayqueuelength()
  1206. {
  1207. $dtype = 'user.queue.day.length';
  1208. $today = date("Y-m-d");
  1209. $sret = self::$db->select('*')->from('ws_countmidtable')->where('dtype=:dtype and mdate=:mdate')->bindValues(array('dtype' => $dtype, 'mdate' => $today))->row();
  1210. if ($sret) {
  1211. self::$db->update('ws_countmidtable')->cols(array('dcontent' => intval($sret['dcontent']) + 1))->where('id=' . $sret['id'])->query();
  1212. } else {
  1213. self::$db->insert('ws_countmidtable')->cols(array(
  1214. 'dtype' => $dtype,
  1215. 'mdate' => $today,
  1216. 'datatype' => 1,
  1217. 'dcontent' => 1))->query();
  1218. }
  1219. }
  1220. //客服工单转单
  1221. private static function servicetrutoother($type, $owen, $otherkfid, $serverid, $clientuid)
  1222. {
  1223. $db->insert('ws_serviceturn_log')->cols(array(
  1224. 'stype' => $type,
  1225. 'uid' => $owen,
  1226. 'tuid' => $otherkfid,
  1227. 'serverid' => $serverid,
  1228. 'guestuid' => $clientuid
  1229. ))->query();
  1230. }
  1231. /**
  1232. * 给客服分配会员【均分策略】
  1233. * @param $kfList
  1234. * @param $userList
  1235. * @param $group
  1236. * @param $total
  1237. */
  1238. private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
  1239. {
  1240. // 注:修改为已上线(status为1上线status为2不接受分配)
  1241. $onlineKF = [];
  1242. foreach ($kfList as $k => $v) {
  1243. foreach ($v as $ke => $va) {
  1244. if ($va['status'] == 1) {
  1245. $onlineKF[$k][$ke] = $va;
  1246. }
  1247. }
  1248. }
  1249. // 没有客服上线
  1250. if (empty($onlineKF) || empty($onlineKF[$group])) {
  1251. return ['code' => -1];
  1252. }
  1253. // 没有待分配的会员
  1254. if (empty($userList)) {
  1255. return ['code' => -2];
  1256. }
  1257. // 未设置每个客服可以服务多少人
  1258. if (0 == $total) {
  1259. return ['code' => -3];
  1260. }
  1261. // 查看该组的客服是否在线
  1262. if (!isset($onlineKF[$group])) {
  1263. return ['code' => -1];
  1264. }
  1265. //上次用户掉线后,还可以继续上一次 (如果没有关闭) 的会话 --1
  1266. $odltalksession = false;
  1267. $user = $user_first = array_shift($userList);
  1268. if ($uid > 0 && $user['id'] != $uid && count($userList) > 1) {
  1269. $timevalielimit = time() - 60 * 5;
  1270. $odltalksession = self::$db->select('*')->from('ws_service_log')->where('user_id=:uid and `group`=:group and `status`=3 and end_time>=:timevalielimit"')->bindValues(array('uid' => $uid, 'group' => $group, 'timevalielimit' => $timevalielimit))->row();
  1271. if ($odltalksession) {
  1272. foreach ($userList as $ttkey => $ttval) {
  1273. if ($ttval['id'] == $uid) {
  1274. array_unshift($userList, $user);
  1275. $user = $userList[$ttkey];
  1276. unset($userList[$ttkey]);
  1277. break;
  1278. }
  1279. }
  1280. }
  1281. }
  1282. //上次用户掉线后,还可以继续上一次 (如果没有关闭) 的会话 --2
  1283. if ($odltalksession) {
  1284. $oldkrid = 'KF' . $odltalksession['kf_id'];
  1285. if (isset($onlineKF[$group][$oldkrid])) {
  1286. $kf = $onlineKF[$group][$oldkrid];
  1287. $min = $kf['task'];
  1288. $flag = $kf['id'];
  1289. unset($onlineKF[$group][$oldkrid]);
  1290. } else {
  1291. goto NOSIGNKF;
  1292. }
  1293. } else {
  1294. NOSIGNKF:
  1295. $kf = $onlineKF[$group];
  1296. $kf = array_shift($kf);
  1297. $min = $kf['task'];
  1298. $flag = $kf['id'];
  1299. foreach ($onlineKF[$group] as $key => $vo) {
  1300. if ($vo['task'] < $min) {
  1301. $min = $vo['task'];
  1302. $flag = $key;
  1303. }
  1304. }
  1305. unset($kf);
  1306. }
  1307. // 需要排队了
  1308. if ($onlineKF[$group][$flag]['task'] == $total) {
  1309. array_unshift($userList, $user);
  1310. return ['code' => -4];
  1311. }
  1312. $kfList[$group][$flag]['task'] += 1;
  1313. array_push($kfList[$group][$flag]['user_info'], $user['client_id']); // 被分配的用户信息
  1314. return [
  1315. 'code' => 1,
  1316. 'data' => [
  1317. $onlineKF[$group][$flag]['id'],
  1318. $onlineKF[$group][$flag]['name'],
  1319. $onlineKF[$group][$flag]['client_id'],
  1320. $user,
  1321. $kfList,
  1322. $userList
  1323. ]
  1324. ];
  1325. }
  1326. /**
  1327. * 获取最大的服务人数
  1328. * @return int
  1329. */
  1330. private static function getMaxServiceNum()
  1331. {
  1332. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  1333. if (!empty($maxNumber)) {
  1334. $maxNumber = 5;
  1335. } else {
  1336. $maxNumber = $maxNumber['0']['max_service'];
  1337. }
  1338. return $maxNumber;
  1339. }
  1340. /**
  1341. * 将内存中的数据写入统计表
  1342. * @param int $flag
  1343. */
  1344. private static function writeLog($flag = 1)
  1345. {
  1346. // 上午 8点 到 22 点开始统计
  1347. if (date('H') < 8 || date('H') > 22) {
  1348. return;
  1349. }
  1350. // 当前正在接入的人 和 在线客服数
  1351. $kfList = self::$global->kfList;
  1352. $nowTalking = 0;
  1353. $onlineKf = 0;
  1354. if (!empty($kfList)) {
  1355. foreach ($kfList as $key => $vo) {
  1356. $onlineKf += count($vo);
  1357. foreach ($vo as $k => $v) {
  1358. $nowTalking += count($v['user_info']);
  1359. }
  1360. }
  1361. }
  1362. // 在队列中的用户
  1363. $inQueue = count(self::$global->userList);
  1364. $key = date('Ymd') . 'total_in';
  1365. $key2 = date('Ymd') . 'success_in';
  1366. $param = [
  1367. 'is_talking' => $nowTalking,
  1368. 'in_queue' => $inQueue,
  1369. 'online_kf' => $onlineKf,
  1370. 'success_in' => self::$global->$key2,
  1371. 'total_in' => self::$global->$key,
  1372. 'now_date' => date('Y-m-d')
  1373. ];
  1374. self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
  1375. if (2 == $flag) {
  1376. $param = [
  1377. 'is_talking' => $nowTalking,
  1378. 'in_queue' => $inQueue,
  1379. 'online_kf' => $onlineKf,
  1380. 'success_in' => self::$global->$key2,
  1381. 'total_in' => self::$global->$key,
  1382. 'add_date' => date('Y-m-d'),
  1383. 'add_hour' => date('H'),
  1384. 'add_minute' => date('i'),
  1385. ];
  1386. self::$db->insert('ws_service_data')->cols($param)->query();
  1387. }
  1388. unset($kfList, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
  1389. }
  1390. /**
  1391. * 机器人问答
  1392. * @param $client_id 服务ID
  1393. * @param $message 数据
  1394. */
  1395. private static function toRobot($client_id, $message)
  1396. {
  1397. $groups_id = $message['data']['groups_id'];
  1398. $robot_name = $message['data']['robot_name'];
  1399. $robotgroups_id = $message['data']['robotgroups_id'];
  1400. // 查询问题.
  1401. $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 . "'");
  1402. $chat_message = [
  1403. 'message_type' => 'robotMessage',
  1404. //'message_type' => 'chatMessage',
  1405. 'data' => [
  1406. 'name' => '智能助手',
  1407. 'time' => date('H:i'),
  1408. 'content' => $getRobot ? $getRobot[0]['robot_content'] : 'error',
  1409. ]
  1410. ];
  1411. sleep(1);
  1412. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1413. }
  1414. /**
  1415. * 评价
  1416. * @param $client_id 服务ID
  1417. * @param $message 数据
  1418. */
  1419. private static function evaluate($client_id, $message)
  1420. {
  1421. // 修改数据库.
  1422. $evaluate_id = $message['data']['evaluate_id'];
  1423. $result = self::$db->query("UPDATE `ws_service_log` SET `evaluate_id` = '" . $evaluate_id . "' WHERE `client_id`='" . $client_id . "'");
  1424. if ($result) {
  1425. $chat_message = [
  1426. 'message_type' => 'evaluate',
  1427. 'data' => [
  1428. 'status' => 1,
  1429. 'time' => date('H:i'),
  1430. ]
  1431. ];
  1432. } else {
  1433. $chat_message = [
  1434. 'message_type' => 'evaluate',
  1435. 'data' => [
  1436. 'status' => 2,
  1437. 'time' => date('H:i'),
  1438. ]
  1439. ];
  1440. }
  1441. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1442. }
  1443. //获取系统配置
  1444. private static function upsystemconfig()
  1445. {
  1446. $systemConfigData = self::$db->query("SELECT * FROM `ws_systemconfig`");
  1447. $arr = [];
  1448. if ($systemConfigData) {
  1449. foreach ($systemConfigData as $item) {
  1450. $arr[$item['systemconfig_enName']] = $item;
  1451. }
  1452. self::$global->systemconfig = $arr;
  1453. }
  1454. $group = self::$db->query("SELECT * FROM `ws_groups`");
  1455. $arr = [];
  1456. if ($group) {
  1457. foreach ($group as $val) {
  1458. $arr[$val['id']] = $val['name'];
  1459. }
  1460. self::$global->groupmap = $arr;
  1461. }
  1462. }
  1463. /**
  1464. * 超时
  1465. * @param $client_id 服务ID
  1466. * @param $message 数据
  1467. */
  1468. private static function overTime()
  1469. {
  1470. // 查询对话时效设置.
  1471. $systemConfigData = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName`,`systemconfig_content` FROM `ws_systemconfig`");
  1472. foreach ($systemConfigData as $k => $v) {
  1473. if ($v['systemconfig_enName'] == 'overtime') {
  1474. self::$global->overtime = $v;
  1475. } elseif ($v['systemconfig_enName'] == 'unoperated') {
  1476. self::$global->unoperated = $v;
  1477. } elseif ($v['systemconfig_enName'] == 'noResponse') {
  1478. self::$global->noResponse = $v;
  1479. }
  1480. }
  1481. // 查询未断开的工单.
  1482. $serviceLog = self::$db->query("SELECT `servicelog_id`,`client_id`,`start_time` FROM `ws_service_log` WHERE `status`='1' OR `status`='3'");
  1483. $whereOr = '1=0';
  1484. foreach ($serviceLog as $k => $v) {
  1485. if ($k == 0) {
  1486. $whereOr = "`servicelog_id`=" . $v['servicelog_id'];
  1487. } else {
  1488. $whereOr .= " OR `servicelog_id`=" . $v['servicelog_id'];
  1489. }
  1490. }
  1491. // 查询最后一次会话.
  1492. //$chatLog = self::$db->query("SELECT `servicelog_id`,MAX(`time_line`) FROM `ws_chat_log` WHERE ".$whereOr." group by `servicelog_id`");
  1493. $chatLog = self::$db->query("
  1494. select * from ws_chat_log as a where time_line=(
  1495. select max(b.time_line) from ws_chat_log as b where a.servicelog_id = b.servicelog_id and (" . $whereOr . ") group by servicelog_id
  1496. )
  1497. ");
  1498. $setOvertime = strtotime('-' . (self::$global->overtime['systemconfig_data'] - 60) . ' second');
  1499. $overtime = strtotime('-' . (self::$global->overtime['systemconfig_data']) . ' second');
  1500. $setUnoperated = strtotime('-' . (self::$global->unoperated['systemconfig_data'] - 60) . ' second');
  1501. $unoperated = strtotime('-' . (self::$global->unoperated['systemconfig_data']) . ' second');
  1502. $noResponse = strtotime('-' . (self::$global->noResponse['systemconfig_data']) . ' second');
  1503. foreach ($serviceLog as $k => $v) {
  1504. if (!strlen(array_search($v['servicelog_id'], array_column($chatLog, 'servicelog_id')))) {
  1505. // 如果小于设定时间则关闭会话.
  1506. if ($v['start_time'] <= $unoperated) {
  1507. self::serverClose($v['client_id'], $v['servicelog_id']);
  1508. // 如果小于设定时间前一分钟则给出提示.
  1509. } elseif ($v['start_time'] <= $setUnoperated) {
  1510. $chat_message = [
  1511. 'message_type' => 'overtime',
  1512. 'data' => [
  1513. 'content' => self::$global->unoperated['systemconfig_content'],
  1514. ]
  1515. ];
  1516. Gateway::sendToClient($v['client_id'], json_encode($chat_message, 256));
  1517. }
  1518. }
  1519. }
  1520. // 循环检测会话时效.
  1521. foreach ($chatLog as $k => $v) {
  1522. $toWho = substr($v['to_id'], 0, 2);
  1523. // 如果对话为客服的最后一次对话且时间小于设定时间则结束工单.
  1524. if ($v['time_line'] <= $overtime) {
  1525. $found_key = array_search($v['servicelog_id'], array_column($serviceLog, 'servicelog_id'));
  1526. self::serverClose($serviceLog[$found_key]['client_id'], $v['servicelog_id']);
  1527. // 如果对话为客服的最后一次对话且时间小于设定时间前一分钟则给出提示.
  1528. } elseif ($v['time_line'] <= $setOvertime) {
  1529. $chat_message = [
  1530. 'message_type' => 'overtime',
  1531. 'data' => [
  1532. 'content' => self::$global->overtime['systemconfig_content'],
  1533. ]
  1534. ];
  1535. $found_key = array_search($v['servicelog_id'], array_column($serviceLog, 'servicelog_id'));
  1536. Gateway::sendToClient($serviceLog[$found_key]['client_id'], json_encode($chat_message, 256));
  1537. }
  1538. }
  1539. }
  1540. /**
  1541. * 系统监控
  1542. * @param $message 数据
  1543. */
  1544. private static function systemMonitoring($adminList)
  1545. {
  1546. // 查询未结束工单.
  1547. $serviceLog = self::$db->query("select ws_service_log.servicelog_id,ws_users.user_name as server_name,ws_service_log.user_name,kf_id,start_time,end_time,ws_service_log.group_id,evaluate_id,intime,ws_service_log.status,alarm_userSensitive,alarm_serverSensitive,alarm_corresponding
  1548. from `ws_service_log`
  1549. join `ws_alarm` on ws_service_log.servicelog_id=ws_alarm.servicelog_id
  1550. join `ws_users` on ws_service_log.kf_id=ws_users.id
  1551. WHERE ws_service_log.status='1' OR ws_service_log.status='3'");
  1552. // 查询系统设置表.
  1553. $systemconfig = self::$db->query("SELECT `systemconfig_data` FROM `ws_systemconfig` WHERE `systemconfig_enName`='verifyReturnTime' or `systemconfig_enName`='verifyAllTime'");
  1554. $found_key = array_search('verifyReturnTime', array_column($systemconfig, 'systemconfig_enName'));
  1555. // 质检会话响应时长.
  1556. $verifyReturnTime = $systemconfig[$found_key]['systemconfig_data'];
  1557. $found_key = array_search('verifyAllTime', array_column($systemconfig, 'systemconfig_enName'));
  1558. // 质检会话时长.
  1559. $verifyAllTime = $systemconfig[$found_key]['systemconfig_data'];
  1560. // 差评次数.
  1561. $evaluateCount = 0;
  1562. // 未结束工单id.
  1563. $servicelog_ids = '';
  1564. $overtimeNumber = 0; // 会话超时次数.
  1565. $overtimeTime = []; // 会话超时时间.
  1566. $userSensitive = 0; // 用户敏感词报警次数.
  1567. $serverSensitive = 0; // 客服敏感词报警次数.
  1568. $csdNumber = 0; // 响应超时次数.
  1569. $csdTime = []; // 响应超时时间.
  1570. foreach ($serviceLog as $k => $v) {
  1571. // 工单报警总次数.
  1572. $allCount = 0;
  1573. // 差评次数.
  1574. if ($v['evaluate_id'] == 3) {
  1575. $evaluateCount++;
  1576. $allCount++;
  1577. }
  1578. $duration = time() - $v['start_time'];
  1579. // 会话超时.
  1580. if ($duration > $verifyAllTime) {
  1581. $overtimeNumber++;
  1582. $allCount++;
  1583. $overtimeTime[] = $duration;
  1584. }
  1585. // 敏感词报警.
  1586. $userSensitive += $v['alarm_userSensitive'];
  1587. $allCount += $v['alarm_userSensitive'];
  1588. $serverSensitive += $v['alarm_serverSensitive'];
  1589. $allCount += $v['alarm_serverSensitive'];
  1590. // 响应超时.
  1591. if ($v['alarm_corresponding'] > $verifyReturnTime) {
  1592. $csdTime[] = $v['alarm_corresponding'];
  1593. $csdNumber++;
  1594. $allCount++;
  1595. }
  1596. $serviceLog[$k]['allCount'] = $allCount;
  1597. }
  1598. // 查询对话时效设置.
  1599. foreach ($adminList as $v) {
  1600. $chat_message = [
  1601. 'message_type' => 'monitor',
  1602. 'data' => [
  1603. 'cvtList' => $serviceLog,
  1604. 'userSensitive' => $userSensitive,
  1605. 'serverSensitive' => $serverSensitive,
  1606. 'csdNumber' => $csdNumber,
  1607. 'csdTime' => $csdTime,
  1608. 'overtimeNumber' => $overtimeNumber,
  1609. 'overtimeTime' => $overtimeTime,
  1610. 'evaluateCount' => $evaluateCount,
  1611. ]
  1612. ];
  1613. Gateway::sendToClient($v, json_encode($chat_message, 256));
  1614. }
  1615. }
  1616. //客服在线状态写组
  1617. private static function writeLogKfStatus($kf, $status, $flag = 1)
  1618. {
  1619. if ($flag == 1) {
  1620. $status = intval($status);
  1621. if ($status == 0) {
  1622. self::$db->delete('ws_kfonline')->where("uid='$kf'")->query();
  1623. } else {
  1624. $now = date('Y-m-d H:i;s');
  1625. $sql = "insert into ws_kfonline(uid,status,uptime) values('$kf',$status,'$now') ON DUPLICATE KEY UPDATE status=$status,uptime='$now' ";
  1626. self::$db->query($sql);
  1627. }
  1628. } else {
  1629. self::$db->query("delete from ws_kfonline ");
  1630. }
  1631. }
  1632. //用户下线通知
  1633. private static function userCloseNotice($client_id, $cuid, $group)
  1634. {
  1635. }
  1636. //踢掉同一用户的旧用户
  1637. private static function tickOlduser($uid)
  1638. {
  1639. }
  1640. }