Chat.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. <?php
  2. namespace app\controller\v2;
  3. use app\extra\basic\Base;
  4. use app\extra\tools\UploadExtend;
  5. use app\middleware\AuthMiddleware;
  6. use app\model\saas\SaasChatMsg;
  7. use app\model\saas\SaasChatStore;
  8. use app\model\saas\SaasService;
  9. use app\model\saas\SaasStore;
  10. use app\model\saas\SaasUserOpen;
  11. use app\service\saas\ChatStoreService;
  12. use DI\Attribute\Inject;
  13. use LinFly\Annotation\Attributes\Route\Controller;
  14. use LinFly\Annotation\Attributes\Route\GetMapping;
  15. use LinFly\Annotation\Attributes\Route\Middleware;
  16. use LinFly\Annotation\Attributes\Route\PostMapping;
  17. use support\Request;
  18. use support\Response;
  19. use Webman\Push\Api;
  20. #[Controller("/v2/chat"),Middleware(AuthMiddleware::class)]
  21. class Chat extends Base
  22. {
  23. #[Inject]
  24. protected ChatStoreService $service;
  25. /**
  26. * 获取客服列表-已聊过的
  27. * @param Request $request
  28. * @return Response
  29. */
  30. #[GetMapping("list")]
  31. public function getServiceList(Request $request): Response
  32. {
  33. try {
  34. $param = $request->all();
  35. if (!empty($param['size'])) {
  36. $param['pageSize'] = $param['size'];
  37. }
  38. $param['openid'] = $request->user['openid'];
  39. $list = $this->service->setModel()->getList($param,null,true,['last','avatar'],['last' => function($data,$resp) use($param){
  40. $last = (new SaasChatMsg)->where(['poi_id' => $resp['poi_id'],'openid' => $param['openid'],'is_user' => 0])->order("create_at desc")->field("content,create_at,type")->findOrEmpty();
  41. if ($last->isEmpty()) {
  42. return ['type' => "text","content"=>"-",'num' => 0,"create_at"=> formatTime(date("Y-m-d H:i:s",time()))];
  43. }
  44. return ["content"=> str_cut_ellipsis($last['content'],12),'num' => 0,"create_at"=> formatTime($last['create_at']),'type' => $last['type']];
  45. },'avatar' => function(){
  46. return sConf("service.logo");
  47. }]);
  48. $user = (new SaasUserOpen)->where(['openid' => $param['openid']])->findOrEmpty();
  49. if ($user->isEmpty()) return error("数据错误");
  50. $userState = 1;
  51. if (empty($user['avatar'])) {
  52. $userState = 0;
  53. }
  54. return successTrans("success.data",['data' => pageFormat($list),'user' => $userState]);
  55. } catch (\Throwable $throwable) {
  56. return error($throwable->getMessage());
  57. }
  58. }
  59. /**
  60. * 获取基础客服消息
  61. */
  62. #[GetMapping("service")]
  63. public function getChatStore(Request $request): Response
  64. {
  65. try {
  66. $param = $this->_valid([
  67. "poi.require" => "参数错误",
  68. "size.require" => "参数错误",
  69. "page.require" => "参数错误",
  70. ],$request->method());
  71. if (!is_array($param)) return error($param);
  72. $store = (new SaasStore)->where("poi_id",$param['poi'])->findOrEmpty();
  73. if ($store->isEmpty()) return error("店铺不存在");
  74. $userAvatar = $request->user['avatar'];
  75. // 获取最新的10条聊天记录
  76. $msg = (new SaasChatMsg)->where(['openid' => $request->user['openid'],'poi_id' => $store['poi_id']])
  77. ->append(['time','userType','msgType'])
  78. ->withAttr(['time' => function($resp,$data){
  79. return strtotime($data['create_at']) * 1000;
  80. },'userType' => function($resp,$data){
  81. if ($data['source'] == 1) {
  82. return "self";
  83. } else {
  84. return "friend";
  85. }
  86. },'msgType' => function($resp,$data){
  87. return $data['type'];
  88. }])
  89. ->order("id","desc")
  90. ->paginate([
  91. "list_rows" => $param['size'],
  92. "page" => 1
  93. ]);
  94. $serviceAvatar = sConf("service.logo");
  95. $star = (new SaasService)->where("poi_id",$param['poi'])->with(['quick'])->findOrEmpty();
  96. return success("ok",[
  97. "avatar" => $userAvatar,
  98. "userId" => md5($request->user['openid']),
  99. "msg" => $msg,
  100. "service" => $serviceAvatar,
  101. "store" => [
  102. "shopName" => $store['poi_name'],
  103. "shopId" => $store['poi_id'],
  104. ],
  105. "quick" => $star
  106. ]);
  107. } catch (\Throwable $throwable) {
  108. return error($throwable->getMessage());
  109. }
  110. }
  111. /**
  112. * 历史聊天列表
  113. * @param Request $request
  114. * @return Response
  115. */
  116. #[GetMapping("msg")]
  117. public function getMsgList(Request $request): Response
  118. {
  119. try {
  120. $param = $this->_valid([
  121. "poi.require" => "参数错误",
  122. "size.require" => "参数错误",
  123. "page.require" => "参数错误",
  124. ],$request->method());
  125. if (!is_array($param)) return error($param);
  126. $store = (new SaasStore)->where("poi_id",$param['poi'])->findOrEmpty();
  127. if ($store->isEmpty()) return error("店铺不存在");
  128. $msg = (new SaasChatMsg)->where(['openid' => $request->user['openid'],'poi_id' => $store['poi_id']])
  129. ->append(['time','userType','msgType'])
  130. ->withAttr(['time' => function($resp,$data){
  131. return strtotime($data['create_at']) * 1000;
  132. },'userType' => function($resp,$data){
  133. if ($data['source'] == 1) {
  134. return "self";
  135. } else {
  136. return "friend";
  137. }
  138. },'msgType' => function($resp,$data){
  139. return $data['type'];
  140. }])
  141. ->order("id","desc")
  142. ->paginate([
  143. "list_rows" => $param['size'],
  144. "page" => $param['page']
  145. ]);
  146. return success("ok",['data' => $msg]);
  147. } catch (\Throwable $throwable) {
  148. return error($throwable->getMessage());
  149. }
  150. }
  151. /**
  152. * 转人工
  153. * @return Response|void
  154. */
  155. public function checkServiceUser()
  156. {
  157. try {
  158. } catch (\Throwable $throwable) {
  159. return error($throwable->getMessage());
  160. }
  161. }
  162. /**
  163. * 发送文字消息
  164. * @param Request $request
  165. * @return Response
  166. */
  167. #[PostMapping("text")]
  168. public function sendTextMsg(Request $request): Response
  169. {
  170. try {
  171. $param = $this->_valid([
  172. "content.require" => trans("empty.require"),
  173. "groupId.require" => trans("empty.require"),
  174. "type.require" => trans("empty.require")
  175. ],"post");
  176. if (!is_array($param)) return error($param);
  177. (new SaasChatMsg)->insertGetId([
  178. "source" => 1,
  179. "openid" => $request->user['openid'],
  180. "content" => is_array($param['content'])?json_encode($param['content']):$param['content'],
  181. "type" => $param['type'],
  182. "msgId" => time(),
  183. "poi_id" => $param['groupId'],
  184. "service_id" => '105', // 客服ID
  185. ]);
  186. $chatStore = (new SaasChatStore)->where(['openid' => $request->user['openid'],"service_id" => 105])->with(['user' => function($query){
  187. $query->field("openid,nickname,avatar,mobile,create_at");
  188. }])->append(['avatar'])->withAttr(['avatar' => function () {
  189. return sConf("service.logo");
  190. }])->findOrEmpty();
  191. $total = (new SaasChatMsg)->where(["poi_id" => $chatStore['poi_id'],"service_id" => 105,"openid" => $chatStore['openid'],'is_read' => 0])->count();
  192. if (!$chatStore->isEmpty()) {
  193. $chatStore->last_at = getDateFull();
  194. $chatStore->save();
  195. $chatStore['lastTime'] = formatTime(getDateFull());
  196. $chatStore['last'] = [
  197. "content" => is_array($param['content'])?json_encode($param['content']):str_cut_ellipsis($param['content']),
  198. "type" => $param['type'],
  199. "num" => $total
  200. ];
  201. }
  202. // 推送消息
  203. $api = new Api('http://127.0.0.1:3232', config('plugin.webman.push.app.app_key'),config('plugin.webman.push.app.app_secret'));
  204. $api->trigger("service-105","message",[
  205. "type" => $param['type'],
  206. "content" => is_array($param['content'])?json_encode($param['content']):$param['content'],
  207. "openid" => $request->user['openid'],
  208. "nick" => [],
  209. "user" => [],
  210. "userType" => "friend",
  211. "avatar" => $request->user['avatar'],
  212. "time" => time() * 1000,
  213. "msgId" => md5($request->user['openid'].time()),
  214. "item" => $chatStore->toArray()
  215. ]);
  216. return successTrans("success.data");
  217. } catch (\Throwable $throwable) {
  218. return error($throwable->getMessage());
  219. }
  220. }
  221. /**
  222. * 发送图片消息
  223. * @param Request $request
  224. * @return Response
  225. */
  226. #[PostMapping("image")]
  227. public function sendImageMsg(Request $request): Response
  228. {
  229. try {
  230. $param = $this->_valid([
  231. "groupId.require" => trans("empty.require"),
  232. "type.require" => trans("empty.require"),
  233. "sendId.require" => trans("empty.require"),
  234. ],"post");
  235. if (!is_array($param)) return error($param);
  236. $resp = UploadExtend::uploadFile();
  237. if (!isset($resp[0]['url'])) return error("发送失败");
  238. $param['content'] = $resp[0]['url'];
  239. (new SaasChatMsg)->insertGetId([
  240. "source" => 1,
  241. "openid" => $request->user['openid'],
  242. "content" => is_array($param['content'])?json_encode($param['content']):$param['content'],
  243. "type" => $param['type'],
  244. "msgId" => time(),
  245. "poi_id" => $param['groupId'],
  246. "service_id" => '105', // 客服ID
  247. ]);
  248. $chatStore = (new SaasChatStore)->where(['openid' => $request->user['openid'],"service_id" => 105])->with(['user' => function($query){
  249. $query->field("openid,nickname,avatar,mobile,create_at");
  250. }])->append(['avatar'])->withAttr(['avatar' => function () {
  251. return sConf("service.logo");
  252. }])->findOrEmpty();
  253. $total = (new SaasChatMsg)->where(["poi_id" => $chatStore['poi_id'],"service_id" => 105,"openid" => $chatStore['openid'],'is_read' => 0])->count();
  254. if (!$chatStore->isEmpty()) {
  255. $chatStore->last_at = getDateFull();
  256. $chatStore->save();
  257. $chatStore['lastTime'] = formatTime(getDateFull());
  258. $chatStore['last'] = [
  259. "content" => is_array($param['content'])?json_encode($param['content']):str_cut_ellipsis($param['content']),
  260. "type" => $param['type'],
  261. "num" => $total
  262. ];
  263. }
  264. // 推送消息
  265. $api = new Api('http://127.0.0.1:3232', config('plugin.webman.push.app.app_key'),config('plugin.webman.push.app.app_secret'));
  266. $api->trigger("service-105","message",[
  267. "type" => $param['type'],
  268. "content" => is_array($param['content'])?json_encode($param['content']):$param['content'],
  269. "openid" => $request->user['openid'],
  270. "nick" => [],
  271. "user" => [],
  272. "userType" => "friend",
  273. "avatar" => $request->user['avatar'],
  274. "time" => time() * 1000,
  275. "msgId" => md5($request->user['openid'].time()),
  276. "item" => $chatStore->toArray()
  277. ]);
  278. } catch (\Throwable $throwable) {
  279. return error($throwable->getMessage());
  280. }
  281. }
  282. }