| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339 |
- <?php
- namespace app\controller\v2;
- use app\extra\basic\Base;
- use app\extra\tools\UploadExtend;
- use app\middleware\AuthMiddleware;
- use app\model\saas\SaasChatMsg;
- use app\model\saas\SaasChatStore;
- use app\model\saas\SaasService;
- use app\model\saas\SaasStore;
- use app\model\saas\SaasUserOpen;
- use app\model\system\SystemUser;
- use app\service\saas\ChatStoreService;
- use DI\Attribute\Inject;
- use LinFly\Annotation\Attributes\Route\Controller;
- use LinFly\Annotation\Attributes\Route\GetMapping;
- use LinFly\Annotation\Attributes\Route\Middleware;
- use LinFly\Annotation\Attributes\Route\PostMapping;
- use support\Request;
- use support\Response;
- use Webman\Push\Api;
- #[Controller("/v2/chat"),Middleware(AuthMiddleware::class)]
- class Chat extends Base
- {
- #[Inject]
- protected ChatStoreService $service;
- /**
- * 获取客服列表-已聊过的
- * @param Request $request
- * @return Response
- */
- #[GetMapping("list")]
- public function getServiceList(Request $request): Response
- {
- try {
- $param = $request->all();
- if (!empty($param['size'])) {
- $param['pageSize'] = $param['size'];
- }
- $param['openid'] = $request->user['openid'];
- $list = $this->service->setModel()->getList($param,null,true,['last','avatar'],['last' => function($data,$resp) use($param){
- $last = (new SaasChatMsg)->where(['poi_id' => $resp['poi_id'],'openid' => $param['openid']])->order("create_at","desc")->field("content,create_at,type")->findOrEmpty();
- if ($last->isEmpty()) {
- return ['type' => "text","content"=>"-",'num' => 0,"create_at"=> formatTime(date("Y-m-d H:i:s",time()))];
- }
- return ["content"=> str_cut_ellipsis($last['content'],12),'num' => 0,"create_at"=> formatTime($last['create_at']),'type' => $last['type']];
- },'avatar' => function(){
- return sConf("service.logo");
- }]);
- $user = (new SaasUserOpen)->where(['openid' => $param['openid']])->findOrEmpty();
- if ($user->isEmpty()) return error("数据错误");
- $userState = 1;
- if (empty($user['avatar'])) {
- $userState = 0;
- }
- return successTrans("success.data",['data' => pageFormat($list),'user' => $userState]);
- } catch (\Throwable $throwable) {
- return error($throwable->getMessage());
- }
- }
- /**
- * 获取基础客服消息
- */
- #[GetMapping("service")]
- public function getChatStore(Request $request): Response
- {
- try {
- $param = $this->_valid([
- "poi.require" => "参数错误",
- "size.require" => "参数错误",
- "page.require" => "参数错误",
- "goods.default" => "",
- "order.default" => "",
- ],$request->method());
- if (!is_array($param)) return error($param);
- $store = (new SaasStore)->where("poi_id",$param['poi'])->findOrEmpty();
- if ($store->isEmpty()) return error("店铺不存在");
- $userAvatar = $request->user['avatar'];
- // 获取最新的10条聊天记录
- $msg = (new SaasChatMsg)->where(['openid' => $request->user['openid'],'poi_id' => $store['poi_id']])
- ->append(['time','userType','msgType'])
- ->withAttr(['time' => function($resp,$data){
- return strtotime($data['create_at']) * 1000;
- },'userType' => function($resp,$data){
- if ($data['source'] == 1) {
- return "self";
- } else {
- return "friend";
- }
- },'msgType' => function($resp,$data){
- return $data['type'];
- }])
- ->order("id","desc")
- ->paginate([
- "list_rows" => $param['size'],
- "page" => 1
- ]);
- $serviceAvatar = sConf("service.logo");
- $star = (new SaasService)->where("poi_id",$param['poi'])->with(['quick'])->findOrEmpty();
- // 获取在线客服
- $service = (new SystemUser)->where(['store_id' => $param['poi'],"type" => 3,"is_line" => 1])->order("last_active_at","asc")->findOrEmpty();
- if ($service->isEmpty()) { // 无客服在线
- return success("ok",[
- "avatar" => $userAvatar,
- "userId" => md5($request->user['openid']),
- "msg" => $msg,
- "service" => $serviceAvatar,
- "store" => [
- "shopName" => $store['poi_name'],
- "shopId" => $store['poi_id'],
- ],
- "quick" => $star,
- "chat_id" => 0, // 客服ID
- ]);
- }
- $chatStore = (new SaasChatStore)->where(['poi_id'=> $store['poi_id'],"openid" => $request->user['openid']])->findOrEmpty();
- if ($chatStore->isEmpty()) {
- $chatStore->insertGetId([
- "poi_id" => $store['poi_id'],
- "poi_name" => $store['poi_name'],
- "openid" => $request->user['openid'],
- "nickname" => $request->user['nickname'],
- "service_id" => $service['id'],
- "order" => $param['order']??'',
- "goods" => $param['goods']??'',
- "last_at" => getDateFull()
- ]);
- } else {
- $chatStore->service_id = $service['id'];
- $chatStore->order = $param['order']??'';
- $chatStore->nickname = $request->user['nickname'];
- $chatStore->goods = $param['goods']??'';
- $chatStore->last_at = getDateFull();
- $chatStore->save();
- }
- return success("ok",[
- "avatar" => $userAvatar,
- "userId" => md5($request->user['openid']),
- "msg" => $msg,
- "service" => $serviceAvatar,
- "store" => [
- "shopName" => $store['poi_name'],
- "shopId" => $store['poi_id'],
- ],
- "quick" => $star,
- "chat_id" => $service['id'], // 客服ID
- ]);
- } catch (\Throwable $throwable) {
- return error($throwable->getMessage());
- }
- }
- /**
- * 历史聊天列表
- * @param Request $request
- * @return Response
- */
- #[GetMapping("msg")]
- public function getMsgList(Request $request): Response
- {
- try {
- $param = $this->_valid([
- "poi.require" => "参数错误",
- "size.require" => "参数错误",
- "page.require" => "参数错误",
- ],$request->method());
- if (!is_array($param)) return error($param);
- $store = (new SaasStore)->where("poi_id",$param['poi'])->findOrEmpty();
- if ($store->isEmpty()) return error("店铺不存在");
- $msg = (new SaasChatMsg)->where(['openid' => $request->user['openid'],'poi_id' => $store['poi_id']])
- ->append(['time','userType','msgType'])
- ->withAttr(['time' => function($resp,$data){
- return strtotime($data['create_at']) * 1000;
- },'userType' => function($resp,$data){
- if ($data['source'] == 1) {
- return "self";
- } else {
- return "friend";
- }
- },'msgType' => function($resp,$data){
- return $data['type'];
- }])
- ->order("id","desc")
- ->paginate([
- "list_rows" => $param['size'],
- "page" => $param['page']
- ]);
- return success("ok",['data' => $msg]);
- } catch (\Throwable $throwable) {
- return error($throwable->getMessage());
- }
- }
- /**
- * 转人工
- * @return Response|void
- */
- public function checkServiceUser()
- {
- try {
- } catch (\Throwable $throwable) {
- return error($throwable->getMessage());
- }
- }
- /**
- * 发送文字消息
- * @param Request $request
- * @return Response
- */
- #[PostMapping("text")]
- public function sendTextMsg(Request $request): Response
- {
- try {
- $param = $this->_valid([
- "content.require" => trans("empty.require"),
- "groupId.require" => trans("empty.require"),
- "chatId.require" => trans("empty.require"),
- "type.require" => trans("empty.require")
- ],"post");
- if (!is_array($param)) return error($param);
- (new SaasChatMsg)->insertGetId([
- "source" => 1,
- "openid" => $request->user['openid'],
- "content" => is_array($param['content'])?json_encode($param['content']):$param['content'],
- "type" => $param['type'],
- "msgId" => time(),
- "poi_id" => $param['groupId'],
- "service_id" => $param['chatId'], // 客服ID
- ]);
- $chatStore = (new SaasChatStore)->where(['openid' => $request->user['openid'],"service_id" => $param['chatId']])->with(['user' => function($query){
- $query->field("openid,nickname,avatar,mobile,create_at");
- }])->append(['avatar'])->withAttr(['avatar' => function () {
- return sConf("service.logo");
- }])->findOrEmpty();
- $total = (new SaasChatMsg)->where(["poi_id" => $chatStore['poi_id'],"service_id" => $param['chatId'],"openid" => $chatStore['openid'],'is_read' => 0])->count();
- if (!$chatStore->isEmpty()) {
- $chatStore->last_at = getDateFull();
- $chatStore->save();
- $chatStore['lastTime'] = formatTime(getDateFull());
- $chatStore['last'] = [
- "content" => is_array($param['content'])?json_encode($param['content']):str_cut_ellipsis($param['content']),
- "type" => $param['type'],
- "num" => $total
- ];
- }
- // 推送消息
- $api = new Api('http://127.0.0.1:3232', config('plugin.webman.push.app.app_key'),config('plugin.webman.push.app.app_secret'));
- $api->trigger("service-{$param['chatId']}","message",[
- "type" => $param['type'],
- "content" => is_array($param['content'])?json_encode($param['content']):$param['content'],
- "openid" => $request->user['openid'],
- "nick" => [],
- "user" => [],
- "userType" => "friend",
- "avatar" => $request->user['avatar'],
- "time" => time() * 1000,
- "msgId" => md5($request->user['openid'].time()),
- "item" => $chatStore->toArray()
- ]);
- return successTrans("success.data");
- } catch (\Throwable $throwable) {
- return error($throwable->getMessage());
- }
- }
- /**
- * 发送图片消息
- * @param Request $request
- * @return Response
- */
- #[PostMapping("image")]
- public function sendImageMsg(Request $request): Response
- {
- try {
- $param = $this->_valid([
- "groupId.require" => trans("empty.require"),
- "type.require" => trans("empty.require"),
- "chatId.require" => trans("empty.require"),
- ],"post");
- if (!is_array($param)) return error($param);
- $resp = UploadExtend::uploadFile();
- if (!isset($resp[0]['url'])) return error("发送失败");
- $param['content'] = $resp[0]['url'];
- (new SaasChatMsg)->insertGetId([
- "source" => 1,
- "openid" => $request->user['openid'],
- "content" => is_array($param['content'])?json_encode($param['content']):$param['content'],
- "type" => $param['type'],
- "msgId" => time(),
- "poi_id" => $param['groupId'],
- "service_id" => $param['chatId'], // 客服ID
- ]);
- $chatStore = (new SaasChatStore)->where(['openid' => $request->user['openid'],"service_id" => $param['chatId']])->with(['user' => function($query){
- $query->field("openid,nickname,avatar,mobile,create_at");
- }])->append(['avatar'])->withAttr(['avatar' => function () {
- return sConf("service.logo");
- }])->findOrEmpty();
- $total = (new SaasChatMsg)->where(["poi_id" => $chatStore['poi_id'],"service_id" => $param['chatId'],"openid" => $chatStore['openid'],'is_read' => 0])->count();
- if (!$chatStore->isEmpty()) {
- $chatStore->last_at = getDateFull();
- $chatStore->save();
- $chatStore['lastTime'] = formatTime(getDateFull());
- $chatStore['last'] = [
- "content" => is_array($param['content'])?json_encode($param['content']):str_cut_ellipsis($param['content']),
- "type" => $param['type'],
- "num" => $total
- ];
- }
- // 推送消息
- $api = new Api('http://127.0.0.1:3232', config('plugin.webman.push.app.app_key'),config('plugin.webman.push.app.app_secret'));
- $api->trigger("service-{$param['chatId']}","message",[
- "type" => $param['type'],
- "content" => is_array($param['content'])?json_encode($param['content']):$param['content'],
- "openid" => $request->user['openid'],
- "nick" => [],
- "user" => [],
- "userType" => "friend",
- "avatar" => $request->user['avatar'],
- "time" => time() * 1000,
- "msgId" => md5($request->user['openid'].time()),
- "item" => $chatStore->toArray()
- ]);
- } catch (\Throwable $throwable) {
- return error($throwable->getMessage());
- }
- }
- }
|