OrderService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2017~2021 LARAVEL研发中心
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://www.laravel.cn
  8. // +----------------------------------------------------------------------
  9. // | Author: laravel开发员 <laravel.qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace App\Services\Api;
  12. use App\Models\GoodsModel;
  13. use App\Models\MemberModel;
  14. use App\Models\OrderGoodsModel;
  15. use App\Models\OrderModel;
  16. use App\Models\StoreModel;
  17. use App\Services\BaseService;
  18. use App\Services\ConfigService;
  19. use App\Services\PaymentService;
  20. use App\Services\RedisService;
  21. use Illuminate\Support\Facades\DB;
  22. /**
  23. * 订单-服务类
  24. * @author laravel开发员
  25. * @since 2020/11/11
  26. * @package App\Services\Api
  27. */
  28. class OrderService extends BaseService
  29. {
  30. // 静态对象
  31. protected static $instance = null;
  32. /**
  33. * 构造函数
  34. * @author laravel开发员
  35. * @since 2020/11/11
  36. */
  37. public function __construct()
  38. {
  39. $this->model = new OrderModel();
  40. }
  41. /**
  42. * 静态入口
  43. */
  44. public static function make()
  45. {
  46. if (!self::$instance) {
  47. self::$instance = new static();
  48. }
  49. return self::$instance;
  50. }
  51. /**
  52. * 订单列表
  53. * @param $params
  54. * @param int $pageSize
  55. * @return array
  56. */
  57. public function getDataList($params, $pageSize = 15)
  58. {
  59. $model = $this->getQuery($params);
  60. // 数据
  61. $list = $model->where(function ($query) use ($params) {
  62. $status = isset($params['status']) ? $params['status'] : 0;
  63. // 进行中
  64. if ($status > 0 && is_array($status)) {
  65. $query->whereIn('a.status', $status);
  66. } else if ($status > 0) {
  67. $query->where('a.status', $status);
  68. }
  69. })->select(['a.*'])
  70. ->orderBy('a.status', 'desc')
  71. ->orderBy('a.create_time', 'desc')
  72. ->orderBy('a.id', 'desc')
  73. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  74. $list = $list ? $list->toArray() : [];
  75. if ($list) {
  76. $statusArr = [1 => '接单中', 2 => '进行中', 3 => '已完成'];
  77. foreach ($list['data'] as &$item) {
  78. $item['create_time'] = $item['create_time'] ? datetime($item['create_time'], 'Y-m-d H:i:s') : '';
  79. $status = isset($item['status']) ? $item['status'] : 0;
  80. $item['status_text'] = '接单中';
  81. if ($status) {
  82. $item['status_text'] = isset($statusArr[$status]) ? $statusArr[$status] : '';
  83. }
  84. $item['goods'] = isset($item['goods']) && $item['goods'] ? $item['goods'] : [];
  85. $item['goods']['shipper_phone_text'] = $item['goods']['shipper_phone'] ? format_mobile($item['goods']['shipper_phone']) : '';
  86. $item['goods']['receiver_phone_text'] = $item['goods']['receiver_phone'] ? format_mobile($item['goods']['receiver_phone']) : '';
  87. }
  88. unset($item);
  89. }
  90. return [
  91. 'pageSize' => $pageSize,
  92. 'total' => isset($list['total']) ? $list['total'] : 0,
  93. 'list' => isset($list['data']) ? $list['data'] : []
  94. ];
  95. }
  96. /**
  97. * 查询条件
  98. * @param $params
  99. * @return mixed
  100. */
  101. public function getQuery($params)
  102. {
  103. $where = ['a.mark' => 1];
  104. return $this->model->from('orders as a')->with(['goods'])
  105. ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
  106. ->where($where)
  107. ->where(function ($query) use ($params) {
  108. $userId = isset($params['user_id']) ? intval($params['user_id']) : 0;
  109. if ($userId > 0) {
  110. $query->where('a.user_id', $userId);
  111. }
  112. })
  113. ->where(function ($query) use ($params) {
  114. $keyword = isset($params['keyword']) ? $params['keyword'] : '';
  115. if ($keyword) {
  116. $query->where('a.order_no', 'like', "%{$keyword}%")
  117. ->orWhere('b.nickname', 'like', "%{$keyword}%")
  118. ->orWhere('b.mobile', 'like', "%{$keyword}%");
  119. }
  120. });
  121. }
  122. /**
  123. * 订单详情
  124. * @param $id
  125. */
  126. public function getOrderInfo($id)
  127. {
  128. $statusArr = [1 => '待审核', 2 => '进行中', 3 => '已完成'];
  129. $info = $this->model->from('orders as a')->with(['goods'])
  130. ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
  131. ->where(['a.id' => $id, 'a.mark' => 1])
  132. ->select(['a.*'])
  133. ->first();
  134. if ($info) {
  135. $info = $info->toArray();
  136. $info['create_time'] = $info['create_time'] ? datetime($info['create_time'], 'Y-m-d H:i:s') : '';
  137. $status = isset($info['status']) ? $info['status'] : 0;
  138. $info['status_text'] = '待付款';
  139. if ($status) {
  140. $info['status_text'] = isset($statusArr[$status]) ? $statusArr[$status] : '';
  141. }
  142. $info['goods'] = isset($info['goods']) && $info['goods'] ? $info['goods'] : [];
  143. $info['goods']['shipper_phone_text'] = $info['goods']['shipper_phone'] ? format_mobile($info['goods']['shipper_phone']) : '';
  144. $info['goods']['receiver_phone_text'] = $info['goods']['receiver_phone'] ? format_mobile($info['goods']['receiver_phone']) : '';
  145. }
  146. return $info;
  147. }
  148. /**
  149. * 创建订单
  150. * @param $userId 用户
  151. * @param $params 参数
  152. * @return array|false
  153. */
  154. public function createOrder($userId, $params)
  155. {
  156. $addressId = isset($params['address_id']) && $params['address_id'] ? $params['address_id'] : 0;
  157. $goods = isset($params['goods']) && $params['goods'] ? $params['goods'] : [];
  158. $ids = $goods ? array_column($goods,'id') : [];
  159. // 参数验证
  160. if (empty($goods) || empty($ids)) {
  161. $this->error = '商品参数不为空';
  162. return false;
  163. }
  164. if ($addressId <= 0) {
  165. $this->error = '请选择收货地址';
  166. return false;
  167. }
  168. // 缓存锁
  169. $cacheLockKey = "caches:orders:submit_lock:{$userId}";
  170. if (RedisService::get($cacheLockKey)) {
  171. $this->error = '订单处理中~';
  172. return false;
  173. }
  174. // 商品数据
  175. $orderNo = get_order_num('GX');
  176. RedisService::set($cacheLockKey, ['params' => $params, 'user_id' => $userId], rand(3, 5));
  177. $result = GoodsService::make()->getOrderGoods($ids, $goods, $orderNo, $userId);
  178. if (empty($result)) {
  179. RedisService::clear($cacheLockKey);
  180. $this->error = GoodsService::make()->getError();
  181. return false;
  182. }
  183. $orderGoods = isset($result['goods']) ? $result['goods'] : [];
  184. $orderTotal = isset($result['total']) ? $result['total'] : 0;
  185. $orderCount = isset($result['count']) ? $result['count'] : 0;
  186. $storeId = isset($result['store_id']) ? $result['store_id'] : 0;
  187. if (empty($orderGoods)) {
  188. RedisService::clear($cacheLockKey);
  189. $this->error = '获取订单商品错误~';
  190. return false;
  191. }
  192. if ($orderTotal <= 0) {
  193. RedisService::clear($cacheLockKey);
  194. $this->error = '订单金额错误~';
  195. return false;
  196. }
  197. if ($orderCount <= 0) {
  198. RedisService::clear($cacheLockKey);
  199. $this->error = '订单商品数量错误~';
  200. return false;
  201. }
  202. // 用户信息
  203. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  204. ->select(['id', 'openid', 'mobile', 'nickname', 'realname', 'balance', 'status'])
  205. ->first();
  206. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  207. $openid = isset($userInfo['openid']) ? $userInfo['openid'] : '';
  208. if (empty($userInfo) || $status != 1) {
  209. $this->error = 1045;
  210. RedisService::clear($cacheLockKey);
  211. return false;
  212. }
  213. if (empty($openid)) {
  214. $this->error = '用户微信未授权,请重新授权登录';
  215. RedisService::clear($cacheLockKey);
  216. return false;
  217. }
  218. // 收货地址信息
  219. $addressInfo = MemberAddressService::make()->getBindInfo($userId, $addressId);
  220. $realname = isset($addressInfo['realname']) ? $addressInfo['realname'] : '';
  221. $mobile = isset($addressInfo['mobile']) ? $addressInfo['mobile'] : '';
  222. $area = isset($addressInfo['area']) ? $addressInfo['area'] : '';
  223. $address = isset($addressInfo['address']) ? $addressInfo['address'] : '';
  224. if (empty($addressInfo) || empty($realname) || empty($mobile) || empty($area) || empty($address)) {
  225. RedisService::clear($cacheLockKey);
  226. $this->error = '收货地址信息错误,请核对后重试~';
  227. return false;
  228. }
  229. // 商家佣金
  230. $storeInfo = StoreModel::where(['id' => $storeId])->first();
  231. $bonusRate = isset($storeInfo['bonus_rate']) ? floatval($storeInfo['bonus_rate']) : 0;
  232. $storeBonusRate = ConfigService::make()->getConfigByCode('store_bonus_rate', 0);
  233. $storeBonusRate = $storeBonusRate > 0 && $storeBonusRate <= 100 ? $storeBonusRate : 0;
  234. $bonusRate = $bonusRate > 0 && $bonusRate <= 100 ? $bonusRate : $storeBonusRate;
  235. $bonus = moneyFormat($orderTotal * $bonusRate, 2);
  236. $orderTotal = 0.1;
  237. // 订单数据
  238. $order = [
  239. 'order_no' => $orderNo,
  240. 'user_id' => $userId,
  241. 'store_id' => $storeId,
  242. 'total' => $orderTotal,
  243. 'num' => $orderCount,
  244. 'pay_total' => $orderTotal,
  245. 'receiver_name' => $realname,
  246. 'receiver_mobile' => $mobile,
  247. 'receiver_area' => $area,
  248. 'receiver_address' => $address,
  249. 'bonus' => $bonus,
  250. 'create_time' => time(),
  251. 'update_time' => time(),
  252. 'status' => 1,
  253. 'mark' => 1,
  254. ];
  255. // 订单处理
  256. DB::beginTransaction();
  257. if (!$orderId = $this->model->insertGetId($order)) {
  258. DB::rollBack();
  259. $this->error = '创建订单失败';
  260. RedisService::clear($cacheLockKey);
  261. return false;
  262. }
  263. // 订单商品
  264. if($orderGoods && !OrderGoodsModel::insert($orderGoods)){
  265. DB::rollBack();
  266. $this->error = '处理订单商品错误';
  267. RedisService::clear($cacheLockKey);
  268. return false;
  269. }
  270. // 获取支付参数
  271. /* TODO 支付处理 */
  272. $payOrder = [
  273. 'type' => 1,
  274. 'order_no' => $orderNo,
  275. 'pay_money' => $orderTotal,
  276. 'body' => '购物消费',
  277. 'openid' => $openid
  278. ];
  279. // 调起支付
  280. $payment = PaymentService::make()->minPay($userInfo, $payOrder, 'store');
  281. if (empty($payment)) {
  282. DB::rollBack();
  283. RedisService::clear($cacheLockKey);
  284. $this->error = PaymentService::make()->getError();
  285. return false;
  286. }
  287. // 用户操作记录
  288. DB::commit();
  289. $this->error = '订单创建成功,请前往支付~';
  290. RedisService::clear($cacheLockKey);
  291. return [
  292. 'order_id' => $orderId,
  293. 'payment' => $payment,
  294. 'total' => $payOrder['pay_money'],
  295. 'pay_type' => 10,
  296. ];
  297. }
  298. /**
  299. * 今日数量统计数据
  300. * @param $userId
  301. * @param int $type
  302. * @return array|mixed
  303. */
  304. public function getCountByDay($userId, $status = 3)
  305. {
  306. $cacheKey = "caches:orders:count_day_{$userId}_{$status}";
  307. $data = RedisService::get($cacheKey);
  308. if ($data) {
  309. return $data;
  310. }
  311. $data = $this->model->where(['user_id' => $userId, 'status' => $status, 'mark' => 1])
  312. ->where('create_time', '>=', strtotime(date('Y-m-d')))
  313. ->count('id');
  314. if ($data) {
  315. RedisService::set($cacheKey, $data, rand(5, 10));
  316. }
  317. return $data;
  318. }
  319. /**
  320. * 订单数
  321. * @param $userId
  322. * @param int $status
  323. * @return array|mixed
  324. */
  325. public function getCountByStatus($userId, $status = 3)
  326. {
  327. $cacheKey = "caches:orders:count_status_{$userId}_{$status}";
  328. $data = RedisService::get($cacheKey);
  329. if ($data) {
  330. return $data;
  331. }
  332. $data = $this->model->where(['user_id' => $userId, 'status' => $status, 'mark' => 1])
  333. ->count('id');
  334. if ($data) {
  335. RedisService::set($cacheKey, $data, rand(5, 10));
  336. }
  337. return $data;
  338. }
  339. /**
  340. * 获取订单审核状态
  341. * @param $userId
  342. * @return array|mixed
  343. */
  344. public function checkOrderStatus($userId)
  345. {
  346. $cacheKey = "caches:orders:checkOrder:{$userId}";
  347. $data = RedisService::get($cacheKey);
  348. if ($data) {
  349. return $data;
  350. }
  351. $data = $this->model->with(['confirm'])->where(function ($query) {
  352. $query->where(function ($query) {
  353. $query->where('status', 2)->where('confirm_at', '>=', date('Y-m-d H:i:s', time() - 3600));
  354. })->orWhere(function ($query) {
  355. $query->where('status', 9)->where('confirm_at', '>=', date('Y-m-d H:i:s', time() - 600));
  356. })->orWhere(function ($query) {
  357. $query->where('status', 3)->where('confirm_at', '>=', date('Y-m-d H:i:s', time() - 600));
  358. })->orWhere('status', 1);
  359. })
  360. ->where(['user_id' => $userId, 'mark' => 1])
  361. ->select(['id', 'order_no', 'user_id', 'goods_id', 'status'])
  362. ->orderBy('id', 'desc')
  363. ->first();
  364. $data = $data ? $data->toArray() : [];
  365. $result = [];
  366. if ($data) {
  367. $orderId = isset($data['id']) ? $data['id'] : 0;
  368. $status = isset($data['status']) ? $data['status'] : 0;
  369. $goodsId = isset($data['goods_id']) ? $data['goods_id'] : 0;
  370. $confirmOrder = isset($data['confirm']) ? $data['confirm'] : [];
  371. $confirmOrderId = isset($confirmOrder['id']) ? $confirmOrder['id'] : 0;
  372. $confirmOrderUser = isset($confirmOrder['user']) ? $confirmOrder['user'] : [];
  373. $realname = isset($confirmOrderUser['realname']) ? $confirmOrderUser['realname'] : '';
  374. if ($status == 9) {
  375. $message = "抱歉,订单已被其他师傅接走";
  376. } else if ($status == 2) {
  377. $message = "恭喜您,抢单成功,请前往完成订单!";
  378. } else if ($status == 3) {
  379. $message = "恭喜您,订单已经完成!";
  380. } else {
  381. $pickerCount = $this->model->where(['goods_id' => $goodsId, 'mark' => 1])->whereIn('status', [1, 2])->count('id');
  382. $pickerCount = $pickerCount <= 3 ? 3 : $pickerCount;
  383. $message = "<p style='padding: 5px 0;'>正在抢单</p><p>({$pickerCount}位师傅正在抢单中)</p>";
  384. }
  385. $result = ['order_id' => $orderId, 'goods_id' => $goodsId, 'confirm_order_id' => $confirmOrderId, 'status' => $status, 'message' => $message];
  386. RedisService::set($cacheKey, $result, rand(10, 20));
  387. }
  388. return $result;
  389. }
  390. }