Service.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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'])->where("openid",$param['openid'])->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"=> $last['content'],'num' => 0,"create_at"=> formatTime($last['create_at']),'type' => $last['type']];
  49. },'avatar' => function(){
  50. return "https://washmy.oss-cn-guangzhou.aliyuncs.com/storage/20260511/23627b2cb8f73a8a90b95c31d726e6ecad0cbb9a.png";
  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']])->append(['avatar','time'])->withAttr(['avatar' => function($data,$resp) use($userAvatar){
  73. if ($resp['source'] == 1) { // 用户
  74. return $userAvatar??'';
  75. } else {
  76. return "https://washmy.oss-cn-guangzhou.aliyuncs.com/storage/20260511/23627b2cb8f73a8a90b95c31d726e6ecad0cbb9a.png";
  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'])->where("type",3)->where("is_line",1)->findOrEmpty();
  86. if ($service->isEmpty()) return $this->encode("ok",['store' => $store,'code' => 3,'sendId' => $request->user['openid'],'msg' => pageFormatMsg($msg),"serviceId" => 0]); // 无客服在线
  87. if ($chatStore->isEmpty()) {
  88. $chatStore->insertGetId([
  89. "poi_id" => $store['poi_id'],
  90. "poi_name" => $store['poi_name'],
  91. "openid" => $request->user['openid'],
  92. "service_id" => $service['id'],
  93. "order" => $param['order']??'',
  94. "goods" => $param['goods']??'',
  95. "last_at" => getDateFull()
  96. ]);
  97. } else {
  98. $chatStore->service_id = $service['id'];
  99. $chatStore->order = $param['order']??'';
  100. $chatStore->goods = $param['goods']??'';
  101. $chatStore->last_at = getDateFull();
  102. $chatStore->save();
  103. }
  104. return $this->encode("ok",['store' => $store,'code' => 1,'sendId' => $request->user['openid'],'msg' => pageFormatMsg($msg),"serviceId" => $service['id'],'avatar' => $userAvatar]); // 客服在线
  105. } catch (\Throwable $throwable) {
  106. echo $throwable->getMessage()."\n";
  107. echo $throwable->getFile()."\n";
  108. echo $throwable->getLine()."\n";
  109. return error($throwable->getMessage());
  110. }
  111. }
  112. #[GetMapping("msg")]
  113. public function getMessageList(Request $request): Response
  114. {
  115. try {
  116. $param = $this->_valid([
  117. "poi.require" => trans("empty.require"),
  118. "page.default" => 1,
  119. "size.default" => 10
  120. ],$request->method());
  121. if (!is_array($param)) return error($param);
  122. $userAvatar = $request->user['avatar'];
  123. $msg = (new SaasChatMsg)->where(['openid' => $request->user['openid'],'poi_id' => $param['poi']])->append(['avatar','time'])->withAttr(['avatar' => function($data,$resp) use($userAvatar){
  124. if ($resp['source'] == 1) {
  125. return $userAvatar??'';
  126. } else {
  127. return "https://washmy.oss-cn-guangzhou.aliyuncs.com/storage/20260511/23627b2cb8f73a8a90b95c31d726e6ecad0cbb9a.png";
  128. }
  129. },'time' => function($resp,$data){
  130. return strtotime($data['create_at']) * 1000;
  131. }])->order("id","desc")->paginate([
  132. "list_rows" => $param['size']??10,
  133. "page" => $param['page']??1,
  134. ]);
  135. return $this->encode("ok",pageFormat($msg));
  136. } catch (\Throwable $throwable) {
  137. return error($throwable->getMessage());
  138. }
  139. }
  140. /**
  141. * 发送消息
  142. * @param Request $request
  143. * @return Response
  144. */
  145. #[PostMapping("send")]
  146. public function sendMsg(Request $request): Response
  147. {
  148. try {
  149. $param = $this->_valid([
  150. "content.require" => trans("empty.require"),
  151. "groupId.require" => trans("empty.require"),
  152. "type.require" => trans("empty.require"),
  153. "sendId.require" => trans("empty.require"),
  154. ],"post");
  155. if (!is_array($param)) return error($param);
  156. (new SaasChatMsg)->insertGetId([
  157. "source" => 1,
  158. "openid" => $request->user['openid'],
  159. "content" => is_array($param['content'])?json_encode($param['content']):$param['content'],
  160. "type" => $param['type'],
  161. "msgId" => time(),
  162. "poi_id" => $param['groupId'],
  163. "service_id" => $param['sendId'],
  164. ]);
  165. $chatStore = (new SaasChatStore)->where(['openid' => $request->user['openid'],"service_id" => $param['sendId']])->with(['user' => function($query){
  166. $query->field("openid,nickname,avatar,mobile,create_at");
  167. }])->append(['last','avatar'])->withAttr(['last' => function($data,$resp) use($param){
  168. $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();
  169. if ($last->isEmpty()) {
  170. return ['type' => "text","content"=>"无",'num' => 0,'time' => time(),"create_at"=> formatTime(date("Y-m-d H:i:s",time()))];
  171. }
  172. $total = (new SaasChatMsg)->where(["poi_id" => $resp['poi_id'],"service_id" => $param['sendId'],"openid" => $resp['openid'],'is_read' => 0])->count();
  173. return ["content"=> str_cut_ellipsis($last['content']),'num' => ($total),"create_at"=> formatTime($last['create_at']),"time"=> strtotime($last['create_at']),'type' => $last['type']];
  174. },'avatar' => function(){
  175. return "https://washmy.oss-cn-guangzhou.aliyuncs.com/storage/20260511/23627b2cb8f73a8a90b95c31d726e6ecad0cbb9a.png";
  176. }])->findOrEmpty();
  177. if (!$chatStore->isEmpty())
  178. {
  179. $chatStore->save(['last_at' => getDateFull()]);
  180. }
  181. $chatStore['last_at'] = getDateFull();
  182. $api = new Api('http://127.0.0.1:3232', config('plugin.webman.push.app.app_key'),config('plugin.webman.push.app.app_secret'));
  183. $api->trigger("service-{$param['sendId']}","message",[
  184. "type" => $param['type'],
  185. "time" => time() * 1000,
  186. "msgId" => time(),
  187. "content" => is_array($param['content'])?json_encode($param['content']):$param['content'],
  188. "source" => 1,
  189. "avatar" => "https://washmy.oss-cn-guangzhou.aliyuncs.com/storage/20260511/23627b2cb8f73a8a90b95c31d726e6ecad0cbb9a.png",
  190. "poi_id" => $param['groupId'],
  191. "openid" => $request->user['openid'],
  192. "service_id" => $param['sendId'],
  193. "create_at" => formatTime(time()),
  194. "last_at" => getDateFull(),
  195. "user" => [
  196. "nickname" => $request->user['nickname'],
  197. "avatar" => $request->user['avatar']
  198. ],
  199. "item" => $chatStore->toArray()
  200. ]);
  201. return successTrans("success.data");
  202. } catch (\Throwable $throwable) {
  203. echo $throwable->getMessage()."\n";
  204. return error($throwable->getMessage());
  205. }
  206. }
  207. /**
  208. * 发送图片消息
  209. * @param Request $request
  210. * @return Response
  211. */
  212. #[PostMapping("send/img")]
  213. public function sendImgMsg(Request $request): Response
  214. {
  215. try {
  216. $resp = UploadExtend::uploadFile();
  217. if (!isset($resp[0]['url'])) return error("发送失败");
  218. $param = $this->_valid([
  219. "groupId.require" => trans("empty.require"),
  220. "type.require" => trans("empty.require"),
  221. "sendId.require" => trans("empty.require"),
  222. ],"post");
  223. if (!is_array($param)) return error($param);
  224. $param['content'] = $resp[0]['url'];
  225. $state = (new SaasChatMsg)->insertGetId([
  226. "source" => 1,
  227. "openid" => $request->user['openid'],
  228. "content" => is_array($param['content'])?json_encode($param['content']):$param['content'],
  229. "type" => $param['type'],
  230. "msgId" => time(),
  231. "poi_id" => $param['groupId'],
  232. "service_id" => $param['sendId'],
  233. ]);
  234. $api = new Api('http://127.0.0.1:3232', config('plugin.webman.push.app.app_key'),config('plugin.webman.push.app.app_secret'));
  235. $api->trigger("service-{$param['sendId']}","message",[
  236. "type" => $param['type'],
  237. "time" => time() * 1000,
  238. "msgId" => time(),
  239. "content" => is_array($param['content'])?json_encode($param['content']):$param['content'],
  240. "source" => 1,
  241. "avatar" => "https://washmy.oss-cn-guangzhou.aliyuncs.com/storage/20260511/23627b2cb8f73a8a90b95c31d726e6ecad0cbb9a.png",
  242. "poi_id" => $param['groupId'],
  243. "openid" => $request->user['openid'],
  244. "service_id" => $param['sendId'],
  245. "create_at" => formatTime(time()),
  246. "user" => [
  247. "nickname" => $request->user['nickname']
  248. ]
  249. ]);
  250. return successTrans("success.data",['path' => $param['content']],200);
  251. } catch (\Throwable $throwable) {
  252. echo $throwable->getMessage()."\n";
  253. return error($throwable->getMessage());
  254. }
  255. }
  256. /**
  257. * 收集完善用户收货地址
  258. * @param Request $request
  259. * @return Response
  260. */
  261. #[PostMapping("send/address")]
  262. public function setOrderAddress(Request $request): Response
  263. {
  264. try {
  265. $param = $this->_valid([
  266. "city.require" => trans("empty.require"),
  267. "mobile.require" => trans("empty.require"),
  268. "mobile.mobile" => trans("error.mobile"),
  269. "address.require" => trans("empty.require"),
  270. "nickname.require" => trans("empty.require"),
  271. "order.require" => trans("empty.require"),
  272. ],$request->method());
  273. if (!is_array($param)) return error($param);
  274. $cityJson = json_decode($param['city'],true);
  275. $cityCode = [];
  276. foreach ($cityJson as $k => $v){
  277. $cityCode[$k] = $v['value'];
  278. $param['city_text'] .= $v['text'];
  279. }
  280. $param['city_code'] = json_encode($cityCode);
  281. $orderData = json_decode($param['order'],true);
  282. $order = (new SaasOrder)->where("out_trade_no",$orderData["order"])->with(['poi'])->findOrEmpty();
  283. if ($order->isEmpty()) return error("关联订单错误");
  284. if ($order['openid'] <> $request->user['openid']) return error("关联订单错误");
  285. if ($order['status'] <> 1) return error("关联订单错误");
  286. $startTime = $order['poi']['order_start']??'09:00';
  287. $endTime = $order['poi']['order_end']??'22:30';
  288. $startTimeStamp = strtotime("Y-m-d {$startTime}:00");
  289. $endTimeStamp = strtotime("Y-m-d {$endTime}:00");
  290. $address = (new SaasOrderAddress)->where(['openid' => $request->user['openid'],'order_sn' => $orderData['order']])->findOrEmpty();
  291. if (!$address->isEmpty()) return error("请勿重复提交");
  292. $address->insertGetId([
  293. "openid" => $request->user['openid'],
  294. "order_sn" => $orderData['order'],
  295. "city_code" => $param['city_code'],
  296. "city_text" => $param['city_text'],
  297. "mobile" => $param['mobile'],
  298. "address" => $param['address'],
  299. "nickname" => $param['nickname'],
  300. ]);
  301. // 判断是否在核销范围
  302. if (time() > $startTimeStamp && time() < $endTimeStamp) { // 自动核销,订单状态改成待发货
  303. Redis::send("order-done",['order' => $orderData['order']]);
  304. } else { // 写入待核销定时任务队列中
  305. (new SaasOrderDelay)->insertGetId([
  306. "order_sn" => $orderData['order'],
  307. ]);
  308. }
  309. return success("提交成功");
  310. } catch (\Throwable $throwable) {
  311. echo $throwable->getMessage()."\n";
  312. return error($throwable->getMessage());
  313. }
  314. }
  315. }