Chat.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. <?php
  2. namespace app\controller\service;
  3. use app\extra\basic\Base;
  4. use app\middleware\AuthMiddleware;
  5. use app\model\saas\SaasChatMsg;
  6. use app\model\saas\SaasChatStore;
  7. use app\model\system\SystemUser;
  8. use app\service\saas\ChatStoreService;
  9. use app\service\saas\GoodsService;
  10. use DI\Attribute\Inject;
  11. use LinFly\Annotation\Attributes\Route\Controller;
  12. use LinFly\Annotation\Attributes\Route\GetMapping;
  13. use LinFly\Annotation\Attributes\Route\Middleware;
  14. use LinFly\Annotation\Attributes\Route\PostMapping;
  15. use support\Request;
  16. use support\Response;
  17. use think\facade\Db;
  18. use Webman\Push\Api;
  19. #[Controller("/api/chat"),Middleware(AuthMiddleware::class)]
  20. class Chat extends Base
  21. {
  22. protected array $noNeedLogin = ["testData"];
  23. #[Inject]
  24. protected ChatStoreService $service;
  25. #[Inject]
  26. protected SaasChatStore $model;
  27. #[Inject]
  28. protected GoodsService $goodsService;
  29. #[GetMapping('user')]
  30. public function getChatUser(Request $request): Response
  31. {
  32. try {
  33. $param = $request->all();
  34. $param['poi_id'] = $request->user['store_id'];
  35. $param['service_id'] = $request->user['id'];
  36. $param['order'] = "descending";
  37. $param['field'] = "last_at";
  38. if ($param['type'] == 1) {
  39. $param['timeEq'] = date("Y-m-d");
  40. } else {
  41. $param['timeLt'] = date("Y-m-d");
  42. }
  43. unset($param['type']);
  44. $data = $this->service->setModel()->getList($param,['user' => function($query){
  45. $query->field("openid,nickname,avatar,mobile,create_at");
  46. }],true,['avatar','last','lastTime'],['avatar' => function(){
  47. return sConf("service.logo");
  48. },'last' => function ($data,$next) use ($param) {
  49. $map = ['poi_id' => $next['poi_id'], 'service_id' => $param['service_id'], 'openid' => $next['openid']];
  50. $unreadSql = Db::table('saas_chat_msg')
  51. ->where($map)
  52. ->where('is_read', 0)
  53. ->field('COUNT(*)')
  54. ->buildSql();
  55. return (new SaasChatMsg)->where($map)->field(['LEFT(content, 12) as content', 'create_at', 'type', Db::raw($unreadSql . ' AS num')])->order('create_at',"desc")->find();
  56. },'lastTime' => function ($data,$next) {
  57. return formatTime($next['last_at']);
  58. }]);
  59. return successTrans(100010,pageFormat($data),200);
  60. } catch (\Throwable $throwable) {
  61. return error($throwable->getMessage());
  62. }
  63. }
  64. #[GetMapping('order')]
  65. public function getMsgOrder(Request $request): Response
  66. {
  67. try {
  68. $param = $this->_valid([
  69. "msgId.require" => trans("empty.require")
  70. ]);
  71. if (!is_array($param)) return error($param);
  72. $productType = $this->goodsService->productType();
  73. $chatStore = $this->model->where("id",$param['msgId'])->with(['orders' => function($query) use($productType){
  74. $query->field("*")->with(['product' => function($query) use($productType){
  75. $query->field("product_id,product_name,product_type")->append(['types'])->withAttr(['types' => function($query,$resp) use($productType){
  76. $productTypeArr = [];
  77. foreach ($productType as $val) {
  78. $productTypeArr[$val['key']] = $val['name'];
  79. }
  80. return $productTypeArr[$resp['product_type']]??'';
  81. }]);
  82. }]);
  83. }])->findOrEmpty();
  84. if ($chatStore->isEmpty()) return error("error");
  85. return success("ok",['order' => $chatStore['orders']]);
  86. } catch (\Throwable $th) {
  87. return error($th->getMessage());
  88. }
  89. }
  90. #[GetMapping('msg')]
  91. public function getMessageData(Request $request): Response
  92. {
  93. try {
  94. $param = $request->all();
  95. $msg = (new SaasChatMsg)->where(['openid' => $param['openid'],'poi_id' => $request->user['store_id']])->append(['avatar','time','userType','msgType'])->withAttr(['avatar' => function(){
  96. return sConf("service.logo");
  97. },'time' => function($resp,$data){
  98. return strtotime($data['create_at']) * 1000;
  99. },'userType' => function($resp,$data){
  100. if ($data['source'] == 1) {
  101. return "friend";
  102. } else {
  103. return "self";
  104. }
  105. },'msgType' => function($resp,$data){
  106. return $data['type'];
  107. }])->with(['nick' => function ($query) {
  108. $query->field("id,truename");
  109. },'user' => function ($query) {
  110. $query->field("openid,nickname,avatar");
  111. }])->order("id","desc")->paginate([
  112. "list_rows" => $param['size'] ?? 10,
  113. "page" => $param['page'] ?? 1,
  114. ]);
  115. return successTrans(100010,pageFormatMsg($msg),200);
  116. } catch (\Throwable $th) {
  117. return error($th->getMessage());
  118. }
  119. }
  120. #[PostMapping('text')]
  121. public function sendTextMsg(Request $request): Response
  122. {
  123. try {
  124. $param = $this->_valid([
  125. "content.require" => trans("empty.require"),
  126. "groupId.require" => trans("empty.require"),
  127. "openid.require" => trans("empty.require"),
  128. "type.require" => trans("empty.require"),
  129. ],$request->method());
  130. if (!is_array($param)) return error($param);
  131. $str = preg_replace('/\s+/','',$param['content']);
  132. if (empty($str)) return error("请勿发送空消息");
  133. (new SaasChatMsg)->insertGetId([
  134. "source" => 2,
  135. "openid" => $param['openid'],
  136. "content" => is_array($param['content'])?json_encode($param['content']):$param['content'],
  137. "type" => $param['type'],
  138. "msgId" => md5($param['openid'].time()),
  139. "poi_id" => $param['groupId'],
  140. "service_id" => $request->user['id'],
  141. ]);
  142. (new SaasChatMsg)->where(['openid' => $param['openid'],'service_id' => $request->user['id']])->save(['is_read' => 1]);
  143. (new SystemUser)->where("id",$request->user['id'])->update(['last_msg_at' => getDateFull()]);
  144. $api = new Api('http://127.0.0.1:3232', config('plugin.webman.push.app.app_key'),config('plugin.webman.push.app.app_secret'));
  145. $api->trigger("user-".md5($param['openid']),"message",[
  146. "type" => $param['type'],
  147. "content" => is_array($param['content'])?json_encode($param['content']):$param['content'],
  148. "openid" => $param['openid'],
  149. "nick" => [],
  150. "user" => [],
  151. "userType" => "friend",
  152. "avatar" => sConf("service.logo"),
  153. "time" => time() * 1000,
  154. "msgId" => md5($param['openid'].time()),
  155. ]);
  156. return successTrans("success.data",['time' => formatTime(time())]);
  157. } catch (\Throwable $throwable) {
  158. return error($throwable->getMessage());
  159. }
  160. }
  161. #[GetMapping('line')]
  162. public function getUserLine(Request $request): Response
  163. {
  164. try {
  165. $user = (new SystemUser)->where("id",$request->user['id'])->findOrEmpty();
  166. if ($user->isEmpty()) return error("数据不存在");
  167. return success("ok",['line' => $user['is_line']]);
  168. } catch (\Throwable $throwable) {
  169. return error($throwable->getMessage());
  170. }
  171. }
  172. #[PostMapping('line/set')]
  173. public function setUserLine(Request $request): Response
  174. {
  175. try {
  176. $param = $this->_valid([
  177. "status.require" => trans("empty.require"),
  178. ],$request->method());
  179. if (!is_array($param)) return error($param);
  180. $user = (new SystemUser)->where("id",$request->user['id'])->findOrEmpty();
  181. if ($user->isEmpty()) return error("数据不存在");
  182. $user->is_line = $param['status'];
  183. $user->last_active_at = getDateFull();
  184. $state = $user->save();
  185. if (!$state) return error('操作失败');
  186. return success("ok",['line' => $user['is_line']]);
  187. } catch (\Throwable $throwable) {
  188. return error($throwable->getMessage());
  189. }
  190. }
  191. #[GetMapping('search')]
  192. public function searchChat(Request $request): Response
  193. {
  194. try {
  195. $param = $this->_valid([
  196. "key.require" => trans("empty.require"),
  197. "type.require" => trans("empty.require"),
  198. "page.default" => 1,
  199. "size.default" => 10
  200. ],$request->method());
  201. if (!is_array($param)) return error($param);
  202. if ($param['type'] == 'user') {
  203. $data = (new SaasChatStore)->where(['service_id' => $request->user['id']])->where("nickname","like","%{$param['key']}%")->with(['user' => function ($query) {
  204. $query->field("openid,nickname,avatar");
  205. }])->paginate([
  206. "list_rows" => $param['size'],
  207. "page" => $param['page']
  208. ]);
  209. } else {
  210. $data = (new SaasChatMsg)->where(['service_id' => $request->user['id']])->where("content","like","%{$param['key']}%")->with(['user' => function ($query) {
  211. $query->field("openid,nickname,avatar");
  212. }])->paginate([
  213. "list_rows" => $param['size'],
  214. "page" => $param['page']
  215. ]);
  216. }
  217. return success('ok',$data->toArray());
  218. } catch (\Throwable $throwable) {
  219. return error($throwable->getMessage());
  220. }
  221. }
  222. #[PostMapping('check')]
  223. public function searchUserCheck(Request $request): Response
  224. {
  225. try {
  226. $param = $this->_valid([
  227. "openid.require" => trans("empty.require"),
  228. "poi_id.require" => trans("empty.require"),
  229. "service_id.require" => trans("empty.require"),
  230. ],$request->method());
  231. if (!is_array($param)) return error($param);
  232. $data = $this->service->setModel()->getList($param,['user' => function($query){
  233. $query->field("openid,nickname,avatar,mobile,create_at");
  234. }],false,['avatar','last','lastTime'],['avatar' => function(){
  235. return sConf("service.logo");
  236. },'last' => function ($data,$next) use ($param) {
  237. $map = ['poi_id' => $next['poi_id'], 'service_id' => $param['service_id'], 'openid' => $next['openid']];
  238. $unreadSql = Db::table('saas_chat_msg')
  239. ->where($map)
  240. ->where('is_read', 0)
  241. ->field('COUNT(*)')
  242. ->buildSql();
  243. return (new SaasChatMsg)->where($map)->field(['LEFT(content, 12) as content', 'create_at', 'type', Db::raw($unreadSql . ' AS num')])->order('create_at',"desc")->find();
  244. },'lastTime' => function ($data,$next) {
  245. return formatTime($next['last_at']);
  246. }]);
  247. return success('ok',$data);
  248. } catch (\Throwable $throwable) {
  249. return error($throwable->getMessage());
  250. }
  251. }
  252. #[GetMapping('ts')]
  253. public function testData()
  254. {
  255. $api = new Api('http://127.0.0.1:3232', config('plugin.webman.push.app.app_key'),config('plugin.webman.push.app.app_secret'));
  256. $api->trigger("user-".md5("_0001DyNWbn2M-x9ttXGPPZQAydvlcv8-UDd"),"message",[
  257. "type" => "image",
  258. "content" => sConf("service.logo"),
  259. "openid" => "_0001DyNWbn2M-x9ttXGPPZQAydvlcv8-UDd",
  260. "nick" => [],
  261. "user" => [],
  262. "userType" => "friend",
  263. "avatar" => sConf("service.logo"),
  264. "time" => time() * 1000,
  265. "msgId" => time(),
  266. ]);
  267. }
  268. }