Events.php 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859
  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(2);
  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 ($ret) {
  1211. $db->update('ws_countmidtable')->cols(array('dcontent' => intval($sret['dcontent']) + 1))->where('id=' . $sret['id'])->query();
  1212. } else {
  1213. $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. print_r([1, $serviceLog[$found_key]['client_id']]);
  1527. self::serverClose($serviceLog[$found_key]['client_id'], $v['servicelog_id']);
  1528. // 如果对话为客服的最后一次对话且时间小于设定时间前一分钟则给出提示.
  1529. } elseif ($v['time_line'] <= $setOvertime) {
  1530. $chat_message = [
  1531. 'message_type' => 'overtime',
  1532. 'data' => [
  1533. 'content' => self::$global->overtime['systemconfig_content'],
  1534. ]
  1535. ];
  1536. $found_key = array_search($v['servicelog_id'], array_column($serviceLog, 'servicelog_id'));
  1537. Gateway::sendToClient($serviceLog[$found_key]['client_id'], json_encode($chat_message, 256));
  1538. }
  1539. }
  1540. }
  1541. /**
  1542. * 系统监控
  1543. * @param $message 数据
  1544. */
  1545. private static function systemMonitoring($adminList)
  1546. {
  1547. // 查询未结束工单.
  1548. $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
  1549. from `ws_service_log`
  1550. join `ws_alarm` on ws_service_log.servicelog_id=ws_alarm.servicelog_id
  1551. join `ws_users` on ws_service_log.kf_id=ws_users.id
  1552. WHERE ws_service_log.status='1' OR ws_service_log.status='3'");
  1553. // 查询系统设置表.
  1554. $systemconfig = self::$db->query("SELECT `systemconfig_data` FROM `ws_systemconfig` WHERE `systemconfig_enName`='verifyReturnTime' or `systemconfig_enName`='verifyAllTime'");
  1555. $found_key = array_search('verifyReturnTime', array_column($systemconfig, 'systemconfig_enName'));
  1556. // 质检会话响应时长.
  1557. $verifyReturnTime = $systemconfig[$found_key]['systemconfig_data'];
  1558. $found_key = array_search('verifyAllTime', array_column($systemconfig, 'systemconfig_enName'));
  1559. // 质检会话时长.
  1560. $verifyAllTime = $systemconfig[$found_key]['systemconfig_data'];
  1561. // 差评次数.
  1562. $evaluateCount = 0;
  1563. // 未结束工单id.
  1564. $servicelog_ids = '';
  1565. $overtimeNumber = 0; // 会话超时次数.
  1566. $overtimeTime = []; // 会话超时时间.
  1567. $userSensitive = 0; // 用户敏感词报警次数.
  1568. $serverSensitive = 0; // 客服敏感词报警次数.
  1569. $csdNumber = 0; // 响应超时次数.
  1570. $csdTime = []; // 响应超时时间.
  1571. foreach ($serviceLog as $k => $v) {
  1572. // 工单报警总次数.
  1573. $allCount = 0;
  1574. // 差评次数.
  1575. if ($v['evaluate_id'] == 3) {
  1576. $evaluateCount++;
  1577. $allCount++;
  1578. }
  1579. $duration = time() - $v['start_time'];
  1580. // 会话超时.
  1581. if ($duration > $verifyAllTime) {
  1582. $overtimeNumber++;
  1583. $allCount++;
  1584. $overtimeTime[] = $duration;
  1585. }
  1586. // 敏感词报警.
  1587. $userSensitive += $v['alarm_userSensitive'];
  1588. $allCount += $v['alarm_userSensitive'];
  1589. $serverSensitive += $v['alarm_serverSensitive'];
  1590. $allCount += $v['alarm_serverSensitive'];
  1591. // 响应超时.
  1592. if ($v['alarm_corresponding'] > $verifyReturnTime) {
  1593. $csdTime[] = $v['alarm_corresponding'];
  1594. $csdNumber++;
  1595. $allCount++;
  1596. }
  1597. $serviceLog[$k]['allCount'] = $allCount;
  1598. }
  1599. // 查询对话时效设置.
  1600. foreach ($adminList as $v) {
  1601. $chat_message = [
  1602. 'message_type' => 'monitor',
  1603. 'data' => [
  1604. 'cvtList' => $serviceLog,
  1605. 'userSensitive' => $userSensitive,
  1606. 'serverSensitive' => $serverSensitive,
  1607. 'csdNumber' => $csdNumber,
  1608. 'csdTime' => $csdTime,
  1609. 'overtimeNumber' => $overtimeNumber,
  1610. 'overtimeTime' => $overtimeTime,
  1611. 'evaluateCount' => $evaluateCount,
  1612. ]
  1613. ];
  1614. Gateway::sendToClient($v, json_encode($chat_message, 256));
  1615. }
  1616. }
  1617. //客服在线状态写组
  1618. private static function writeLogKfStatus($kf, $status, $flag = 1)
  1619. {
  1620. if ($flag == 1) {
  1621. $status = intval($status);
  1622. if ($status == 0) {
  1623. self::$db->delete('ws_kfonline')->where("uid='$kf'")->query();
  1624. } else {
  1625. $now = date('Y-m-d H:i;s');
  1626. $sql = "insert into ws_kfonline(uid,status,uptime) values('$kf',$status,'$now') ON DUPLICATE KEY UPDATE status=$status,uptime='$now' ";
  1627. self::$db->query($sql);
  1628. }
  1629. } else {
  1630. self::$db->query("delete from ws_kfonline ");
  1631. }
  1632. }
  1633. //用户下线通知
  1634. private static function userCloseNotice($client_id, $cuid, $group)
  1635. {
  1636. }
  1637. //踢掉同一用户的旧用户
  1638. private static function tickOlduser($uid)
  1639. {
  1640. }
  1641. }