| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- <?php
- namespace app\admin\command;
- use think\console\Command;
- use think\console\Input;
- use think\console\Output;
- use app\admin\model\User;
- use app\admin\model\Config;
- use app\admin\model\KefuWork;
- use app\enterprise\model\{Message,Friend};
- use Exception;
- use think\facade\Db;
- /**
- * Worker 命令行类
- */
- class UserQueue extends Command
- {
- public function configure()
- {
- $this->setName('user:queue')
- ->setDescription('用户排队,自动分配客服');
- }
- public function execute(Input $input, Output $output)
- {
- $where = [
- ['status', '=', 1],
- ['is_online', '=', 1],
- ['role', '=', 3],
- ];
- while(true) {
- //查询当前最少接线数的客服
- $kefu_chat_max = Config::getKefuChatMax();//单个客服接线上限
- if ($kefu_chat_max) {
- $where[] = ['chat_num', '<', $kefu_chat_max];
- }
- //排队用户
- $list = User::where('status', 1)->where('is_online', 1)->where('service_status', 1)
- ->order('service_start', 'asc')
- ->select()
- ->toArray();
- if (empty($list)) {
- sleep(10);
- }
- foreach ($list as $item) {
- $cs_user = User::where($where)->order('chat_num', 'asc')->find();
- if (!$cs_user) {
- break;
- }
- $this->handleChat($item, $cs_user->user_id, $cs_user->uid);
- }
- }
- }
- /**
- * 自动接线
- */
- public function handleChat($user, $cs_uid, $admin_id)
- {
- try {
- Db::startTrans();
- $user_id = $user['user_id'];
- $user->cs_uid = $cs_uid;
- $user->service_status = 1;
- $user->service_start = time();
- $user->timeout_type = 0;
- $user->save();
-
- //更新客服接线数量
- User::where('user_id', $cs_uid)->update(['chat_num'=>Db::raw('chat_num+1')]);
- //客服接线次数更新
- KefuWork::addNum($admin_id, 'chat_num');
- $friend = Friend::where('create_user', $user_id)->order('create_time', 'desc')->find();
- if ($friend) {
- $robot_id = $friend->friend_user_id;
- $friend->friend_user_id = $cs_uid;
- $friend->save();
- $chat_identify = $cs_uid . '-' . $user_id;
- Message::where(['from_user' => $user_id, 'to_user' => $robot_id])->update(['to_user' => $cs_uid, 'chat_identify' => $chat_identify, 'is_read' => 1]);
- Message::where(['from_user' => $robot_id, 'to_user' => $user_id])->update(['from_user' => $cs_uid, 'chat_identify' => $chat_identify, 'is_read' => 1]);
- }
- Db::commit();
- //通知客服已接线
- wsSendMsg(0,'handleChat',['user_id'=>$user_id]);
- } catch (\Exception $e) {
- Db::rollback();
- }
- }
- }
|