Events.php 74 KB

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