Service.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. <?php
  2. namespace app\controller\api;
  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\SaasOrder;
  9. use app\model\saas\SaasOrderAddress;
  10. use app\model\saas\SaasOrderDelay;
  11. use app\model\saas\SaasStore;
  12. use app\model\system\SystemUser;
  13. use app\service\saas\ChatStoreService;
  14. use DI\Attribute\Inject;
  15. use LinFly\Annotation\Attributes\Route\Controller;
  16. use LinFly\Annotation\Attributes\Route\GetMapping;
  17. use LinFly\Annotation\Attributes\Route\Middleware;
  18. use LinFly\Annotation\Attributes\Route\PostMapping;
  19. use support\Request;
  20. use support\Response;
  21. use Webman\Push\Api;
  22. use Webman\RedisQueue\Redis;
  23. use function DI\get;
  24. #[Controller("/dy/service"),Middleware(AuthMiddleware::class)]
  25. class Service extends Base
  26. {
  27. #[Inject]
  28. protected ChatStoreService $service;
  29. /**
  30. * 获取客服列表-已聊过的
  31. * @param Request $request
  32. * @return Response
  33. */
  34. #[GetMapping("list")]
  35. public function getServiceList(Request $request): Response
  36. {
  37. try {
  38. $param = $request->all();
  39. if (!empty($param['size'])) {
  40. $param['pageSize'] = $param['size'];
  41. }
  42. $param['openid'] = $request->user['openid'];
  43. $list = $this->service->setModel()->getList($param,null,true,['last','avatar'],['last' => function($data,$resp) use($param){
  44. $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();
  45. if ($last->isEmpty()) {
  46. return ['type' => "text","content"=>"-",'num' => 0,"create_at"=> formatTime(date("Y-m-d H:i:s",time()))];
  47. }
  48. return ["content"=> str_cut_ellipsis($last['content'],12),'num' => 0,"create_at"=> formatTime($last['create_at']),'type' => $last['type']];
  49. },'avatar' => function(){
  50. return sConf("service.logo");
  51. }]);
  52. return successTrans("success.data",pageFormat($list));
  53. } catch (\Throwable $throwable) {
  54. return error($throwable->getMessage());
  55. }
  56. }
  57. /**
  58. * 分配客服
  59. * @param Request $request
  60. * @return Response
  61. */
  62. #[PostMapping("shareout")]
  63. public function shareUser2Mer(Request $request): Response
  64. {
  65. try {
  66. $param = $request->all();
  67. $store = (new SaasStore)->where("poi_id",$param['poi'])->findOrEmpty();
  68. if ($store->isEmpty()) return error("店铺不存在");
  69. $chatStore = (new SaasChatStore)->where(['poi_id'=> $store['poi_id'],"openid" => $request->user['openid']])->findOrEmpty();
  70. $userAvatar = $request->user['avatar'];
  71. // 获取最新的10条聊天记录
  72. $msg = (new SaasChatMsg)->where(['openid' => $request->user['openid'],'poi_id' => $store['poi_id'],'is_user' => 0])->append(['avatar','time'])->withAttr(['avatar' => function($data,$resp) use($userAvatar){
  73. if ($resp['source'] == 1) { // 用户
  74. return $userAvatar??'';
  75. } else {
  76. return sConf("service.logo");
  77. }
  78. },'time' => function($resp,$data){
  79. return strtotime($data['create_at']) * 1000;
  80. }])->order("id","desc")->paginate([
  81. "list_rows" => 10,
  82. "page" => 1
  83. ]);
  84. // 获取在线客服
  85. $service = (new SystemUser)->where(['store_id' => $param['poi'],"type" => 3,"is_line" => 1])->order("last_msg_at","asc")->findOrEmpty();
  86. if ($service->isEmpty()) return $this->encode("ok",[
  87. 'store' => $store,
  88. 'code' => 3,
  89. 'sendId' => $request->user['openid'],
  90. 'msg' => pageFormatMsg($msg),
  91. "noService" => [
  92. "msg" => "当前无在线客服,请拨打商家电话 {$store['service_mobile']}",
  93. "logo" => sConf("service.logo")
  94. ],
  95. "serviceId" => 0
  96. ]); // 无客服在线
  97. if ($chatStore->isEmpty()) {
  98. $chatStore->insertGetId([
  99. "poi_id" => $store['poi_id'],
  100. "poi_name" => $store['poi_name'],
  101. "openid" => $request->user['openid'],
  102. "nickname" => $request->user['nickname'],
  103. "service_id" => $service['id'],
  104. "order" => $param['order']??'',
  105. "goods" => $param['goods']??'',
  106. "last_at" => getDateFull()
  107. ]);
  108. } else {
  109. $chatStore->service_id = $service['id'];
  110. $chatStore->order = $param['order']??'';
  111. $chatStore->nickname = $request->user['nickname'];
  112. $chatStore->goods = $param['goods']??'';
  113. $chatStore->last_at = getDateFull();
  114. $chatStore->save();
  115. }
  116. return $this->encode("ok",['store' => $store,'code' => 1,'sendId' => $request->user['openid'],'msg' => pageFormatMsg($msg),"serviceId" => $service['id'],'avatar' => $userAvatar]); // 客服在线
  117. } catch (\Throwable $throwable) {
  118. echo $throwable->getMessage()."\n";
  119. echo $throwable->getFile()."\n";
  120. echo $throwable->getLine()."\n";
  121. return error($throwable->getMessage());
  122. }
  123. }
  124. #[GetMapping("msg")]
  125. public function getMessageList(Request $request): Response
  126. {
  127. try {
  128. $param = $this->_valid([
  129. "poi.require" => trans("empty.require"),
  130. "page.default" => 1,
  131. "size.default" => 10
  132. ],$request->method());
  133. if (!is_array($param)) return error($param);
  134. $userAvatar = $request->user['avatar'];
  135. $msg = (new SaasChatMsg)->where(['openid' => $request->user['openid'],'poi_id' => $param['poi'],'is_user' => 0])->append(['avatar','time'])->withAttr(['avatar' => function($data,$resp) use($userAvatar){
  136. if ($resp['source'] == 1) {
  137. return $userAvatar??'';
  138. } else {
  139. return sConf("service.logo");
  140. }
  141. },'time' => function($resp,$data){
  142. return strtotime($data['create_at']) * 1000;
  143. }])->order("id","desc")->paginate([
  144. "list_rows" => $param['size']??10,
  145. "page" => $param['page']??1,
  146. ]);
  147. return $this->encode("ok",pageFormat($msg));
  148. } catch (\Throwable $throwable) {
  149. return error($throwable->getMessage());
  150. }
  151. }
  152. /**
  153. * 发送消息
  154. * @param Request $request
  155. * @return Response
  156. */
  157. #[PostMapping("send")]
  158. public function sendMsg(Request $request): Response
  159. {
  160. try {
  161. $param = $this->_valid([
  162. "content.require" => trans("empty.require"),
  163. "groupId.require" => trans("empty.require"),
  164. "type.require" => trans("empty.require"),
  165. "sendId.require" => trans("empty.require"),
  166. ],"post");
  167. if (!is_array($param)) return error($param);
  168. (new SaasChatMsg)->insertGetId([
  169. "source" => 1,
  170. "openid" => $request->user['openid'],
  171. "content" => is_array($param['content'])?json_encode($param['content']):$param['content'],
  172. "type" => $param['type'],
  173. "msgId" => time(),
  174. "poi_id" => $param['groupId'],
  175. "service_id" => $param['sendId'],
  176. ]);
  177. $chatStore = (new SaasChatStore)->where(['openid' => $request->user['openid'],"service_id" => $param['sendId']])->with(['user' => function($query){
  178. $query->field("openid,nickname,avatar,mobile,create_at");
  179. }])->append(['last','avatar'])->withAttr(['last' => function($data,$resp) use($param){
  180. $last = (new SaasChatMsg)->where(["poi_id" => $resp['poi_id'],"service_id" => $param['sendId'],"openid" => $resp['openid']])->order("create_at desc")->field("content,create_at,type")->findOrEmpty();
  181. if ($last->isEmpty()) {
  182. return ['type' => "text","content"=>"无",'num' => 0,'time' => time(),"create_at"=> formatTime(date("Y-m-d H:i:s",time()))];
  183. }
  184. $total = (new SaasChatMsg)->where(["poi_id" => $resp['poi_id'],"service_id" => $param['sendId'],"openid" => $resp['openid'],'is_read' => 0])->count();
  185. return ["content"=> str_cut_ellipsis($last['content']),'num' => ($total),"create_at"=> formatTime($last['create_at']),"time"=> strtotime($last['create_at']),'type' => $last['type']];
  186. },'avatar' => function(){
  187. return sConf("service.logo");
  188. }])->findOrEmpty();
  189. if (!$chatStore->isEmpty())
  190. {
  191. $chatStore->save(['last_at' => getDateFull()]);
  192. }
  193. $chatStore['last_at'] = getDateFull();
  194. $api = new Api('http://127.0.0.1:3232', config('plugin.webman.push.app.app_key'),config('plugin.webman.push.app.app_secret'));
  195. $api->trigger("service-{$param['sendId']}","message",[
  196. "type" => $param['type'],
  197. "time" => time() * 1000,
  198. "msgId" => time(),
  199. "content" => is_array($param['content'])?json_encode($param['content']):$param['content'],
  200. "source" => 1,
  201. "avatar" => sConf("service.logo"),
  202. "poi_id" => $param['groupId'],
  203. "openid" => $request->user['openid'],
  204. "service_id" => $param['sendId'],
  205. "create_at" => formatTime(time()),
  206. "last_at" => getDateFull(),
  207. "user" => [
  208. "nickname" => $request->user['nickname'],
  209. "avatar" => $request->user['avatar']
  210. ],
  211. "item" => $chatStore->toArray()
  212. ]);
  213. return successTrans("success.data");
  214. } catch (\Throwable $throwable) {
  215. echo $throwable->getMessage()."\n";
  216. return error($throwable->getMessage());
  217. }
  218. }
  219. /**
  220. * 发送图片消息
  221. * @param Request $request
  222. * @return Response
  223. */
  224. #[PostMapping("send/img")]
  225. public function sendImgMsg(Request $request): Response
  226. {
  227. try {
  228. $resp = UploadExtend::uploadFile();
  229. if (!isset($resp[0]['url'])) return error("发送失败");
  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. $param['content'] = $resp[0]['url'];
  237. $state = (new SaasChatMsg)->insertGetId([
  238. "source" => 1,
  239. "openid" => $request->user['openid'],
  240. "content" => is_array($param['content'])?json_encode($param['content']):$param['content'],
  241. "type" => $param['type'],
  242. "msgId" => time(),
  243. "poi_id" => $param['groupId'],
  244. "service_id" => $param['sendId'],
  245. ]);
  246. $api = new Api('http://127.0.0.1:3232', config('plugin.webman.push.app.app_key'),config('plugin.webman.push.app.app_secret'));
  247. $api->trigger("service-{$param['sendId']}","message",[
  248. "type" => $param['type'],
  249. "time" => time() * 1000,
  250. "msgId" => time(),
  251. "content" => is_array($param['content'])?json_encode($param['content']):$param['content'],
  252. "source" => 1,
  253. "avatar" => sConf("service.logo"),
  254. "poi_id" => $param['groupId'],
  255. "openid" => $request->user['openid'],
  256. "service_id" => $param['sendId'],
  257. "create_at" => formatTime(time()),
  258. "user" => [
  259. "nickname" => $request->user['nickname']
  260. ]
  261. ]);
  262. return successTrans("success.data",['path' => $param['content']],200);
  263. } catch (\Throwable $throwable) {
  264. echo $throwable->getMessage()."\n";
  265. return error($throwable->getMessage());
  266. }
  267. }
  268. /**
  269. * 收集完善用户收货地址
  270. * @param Request $request
  271. * @return Response
  272. */
  273. #[PostMapping("send/address")]
  274. public function setOrderAddress(Request $request): Response
  275. {
  276. try {
  277. $param = $this->_valid([
  278. "city.require" => trans("empty.require"),
  279. "mobile.require" => trans("empty.require"),
  280. "mobile.mobile" => trans("error.mobile"),
  281. "address.require" => trans("empty.require"),
  282. "nickname.require" => trans("empty.require"),
  283. "order.require" => trans("empty.require"),
  284. ],$request->method());
  285. if (!is_array($param)) return error($param);
  286. echo getDateFull()."===地址信息\n";
  287. print_r($param);
  288. $cityJson = json_decode($param['city'],true);
  289. $cityCode = [];
  290. $city_text = "";
  291. foreach ($cityJson as $k => $v){
  292. $cityCode[$k] = $v['value'];
  293. $city_text .= $v['text'];
  294. }
  295. $param['city_text'] = $city_text;
  296. $param['city_code'] = json_encode($cityCode);
  297. $orderData = json_decode($param['order'],true);
  298. $order = (new SaasOrder)->where("out_order_no",$orderData["order"])->with(['poi'])->findOrEmpty();
  299. if ($order->isEmpty()) return error("关联订单错误");
  300. if ($order['openid'] <> $request->user['openid']) return error("关联订单错误");
  301. if ($order['status'] <> 1) return error("关联订单错误");
  302. $startTime = $order['poi']['order_start']??'09:00';
  303. $endTime = $order['poi']['order_end']??'22:30';
  304. $startTimeStamp = strtotime("Y-m-d {$startTime}:00");
  305. $endTimeStamp = strtotime("Y-m-d {$endTime}:00");
  306. $address = (new SaasOrderAddress)->where(['openid' => $request->user['openid'],'order_sn' => $orderData['order']])->findOrEmpty();
  307. if (!$address->isEmpty()) return error("请勿重复提交");
  308. $address->insertGetId([
  309. "openid" => $request->user['openid'],
  310. "order_sn" => $orderData['order'],
  311. "city_code" => $param['city_code'],
  312. "city_text" => $param['city_text'],
  313. "mobile" => $param['mobile'],
  314. "address" => $param['address'],
  315. "nickname" => $param['nickname'],
  316. ]);
  317. $order->status = 2;
  318. $order->express_status = 1;
  319. $order->save();
  320. // 判断是否在核销范围
  321. // if (time() > $startTimeStamp && time() < $endTimeStamp) { // 自动核销,订单状态改成待发货
  322. // Redis::send("order-done",['order' => $orderData['order']]);
  323. // } else { // 写入待核销定时任务队列中
  324. // (new SaasOrderDelay)->insertGetId([
  325. // "order_sn" => $orderData['order'],
  326. // ]);
  327. // }
  328. return success("提交成功");
  329. } catch (\Throwable $throwable) {
  330. echo $throwable->getMessage()."\n";
  331. return error($throwable->getMessage());
  332. }
  333. }
  334. }