OrderService.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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', 'asc')
  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 => '待收货',4=>'确认收货'];
  77. $refundStatusArr = [1 => '已退款', 2 => '退款中', 3 => '退款审核',4=>'退款驳回'];
  78. foreach ($list['data'] as &$item) {
  79. $item['create_time'] = $item['create_time'] ? datetime($item['create_time'], 'Y/m/d H:i') : '';
  80. $status = isset($item['status']) ? $item['status'] : 0;
  81. $item['status_text'] = '待支付';
  82. if ($status) {
  83. $item['status_text'] = isset($statusArr[$status]) ? $statusArr[$status] : '';
  84. }
  85. if($item['refund_status']>0){
  86. $item['status_text'] = isset($refundStatusArr[$item['refund_status']]) ? $refundStatusArr[$item['refund_status']] : $item['status_text'];
  87. }
  88. $item['goods'] = isset($item['goods']) && $item['goods'] ? $item['goods'] : [];
  89. }
  90. unset($item);
  91. }
  92. return [
  93. 'pageSize' => $pageSize,
  94. 'total' => isset($list['total']) ? $list['total'] : 0,
  95. 'list' => isset($list['data']) ? $list['data'] : []
  96. ];
  97. }
  98. /**
  99. * 查询条件
  100. * @param $params
  101. * @return mixed
  102. */
  103. public function getQuery($params)
  104. {
  105. $where = ['a.mark' => 1];
  106. return $this->model->from('orders as a')->with(['orderGoods','store'])
  107. ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
  108. ->where($where)
  109. ->where(function ($query) use ($params) {
  110. $userId = isset($params['user_id']) ? intval($params['user_id']) : 0;
  111. if ($userId > 0) {
  112. $query->where('a.user_id', $userId);
  113. }
  114. })
  115. ->where(function ($query) use ($params) {
  116. $keyword = isset($params['keyword']) ? $params['keyword'] : '';
  117. if ($keyword) {
  118. $query->where('a.order_no', 'like', "%{$keyword}%")
  119. ->orWhere('b.mobile', 'like', "%{$keyword}%");
  120. }
  121. });
  122. }
  123. /**
  124. * 订单详情
  125. * @param $id
  126. */
  127. public function getOrderInfo($id)
  128. {
  129. $statusArr = [1 => '待支付', 2 => '待发货', 3 => '待收货',4=>'已完成'];
  130. $info = $this->model->from('orders as a')->with(['goods'])
  131. ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
  132. ->where(['a.id' => $id, 'a.mark' => 1])
  133. ->select(['a.*'])
  134. ->first();
  135. if ($info) {
  136. $info = $info->toArray();
  137. $info['create_time'] = $info['create_time'] ? datetime($info['create_time'], 'Y-m-d H:i:s') : '';
  138. $status = isset($info['status']) ? $info['status'] : 0;
  139. $info['status_text'] = '待付款';
  140. if ($status) {
  141. $info['status_text'] = isset($statusArr[$status]) ? $statusArr[$status] : '';
  142. }
  143. }
  144. return $info;
  145. }
  146. /**
  147. * 创建订单
  148. * @param $userId 用户
  149. * @param $params 参数
  150. * @return array|false
  151. */
  152. public function createOrder($userId, $params)
  153. {
  154. $addressId = isset($params['address_id']) && $params['address_id'] ? $params['address_id'] : 0;
  155. $goods = isset($params['goods']) && $params['goods'] ? $params['goods'] : [];
  156. $ids = $goods ? array_column($goods,'id') : [];
  157. // 参数验证
  158. if (empty($goods) || empty($ids)) {
  159. $this->error = '商品参数不为空';
  160. return false;
  161. }
  162. if ($addressId <= 0) {
  163. $this->error = '请选择收货地址';
  164. return false;
  165. }
  166. // 缓存锁
  167. $cacheLockKey = "caches:orders:submit_lock:{$userId}";
  168. if (RedisService::get($cacheLockKey)) {
  169. $this->error = '订单处理中~';
  170. return false;
  171. }
  172. // 商品数据
  173. $orderNo = get_order_num('GX');
  174. RedisService::set($cacheLockKey, ['params' => $params, 'user_id' => $userId], rand(3, 5));
  175. $result = GoodsService::make()->getOrderGoods($ids, $goods, $orderNo, $userId);
  176. if (empty($result)) {
  177. RedisService::clear($cacheLockKey);
  178. $this->error = GoodsService::make()->getError();
  179. return false;
  180. }
  181. $orderGoods = isset($result['goods']) ? $result['goods'] : [];
  182. $orderTotal = isset($result['total']) ? $result['total'] : 0;
  183. $orderCount = isset($result['count']) ? $result['count'] : 0;
  184. $storeId = isset($result['store_id']) ? $result['store_id'] : 0;
  185. if (empty($orderGoods)) {
  186. RedisService::clear($cacheLockKey);
  187. $this->error = '获取订单商品错误~';
  188. return false;
  189. }
  190. if ($orderTotal <= 0) {
  191. RedisService::clear($cacheLockKey);
  192. $this->error = '订单金额错误~';
  193. return false;
  194. }
  195. if ($orderCount <= 0) {
  196. RedisService::clear($cacheLockKey);
  197. $this->error = '订单商品数量错误~';
  198. return false;
  199. }
  200. // 用户信息
  201. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  202. ->select(['id', 'openid', 'mobile', 'nickname', 'realname', 'balance', 'status'])
  203. ->first();
  204. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  205. $openid = isset($userInfo['openid']) ? $userInfo['openid'] : '';
  206. if (empty($userInfo) || $status != 1) {
  207. $this->error = 1045;
  208. RedisService::clear($cacheLockKey);
  209. return false;
  210. }
  211. if (empty($openid)) {
  212. $this->error = '用户微信未授权,请重新授权登录';
  213. RedisService::clear($cacheLockKey);
  214. return false;
  215. }
  216. // 收货地址信息
  217. $addressInfo = MemberAddressService::make()->getBindInfo($userId, $addressId);
  218. $realname = isset($addressInfo['realname']) ? $addressInfo['realname'] : '';
  219. $mobile = isset($addressInfo['mobile']) ? $addressInfo['mobile'] : '';
  220. $area = isset($addressInfo['area']) ? $addressInfo['area'] : '';
  221. $address = isset($addressInfo['address']) ? $addressInfo['address'] : '';
  222. if (empty($addressInfo) || empty($realname) || empty($mobile) || empty($area) || empty($address)) {
  223. RedisService::clear($cacheLockKey);
  224. $this->error = '收货地址信息错误,请核对后重试~';
  225. return false;
  226. }
  227. // 商家佣金
  228. $storeInfo = StoreModel::where(['id' => $storeId])->first();
  229. $bonusRate = isset($storeInfo['bonus_rate']) ? floatval($storeInfo['bonus_rate']) : 0;
  230. $storeBonusRate = ConfigService::make()->getConfigByCode('store_bonus_rate', 0);
  231. $storeBonusRate = $storeBonusRate > 0 && $storeBonusRate <= 100 ? $storeBonusRate : 0;
  232. $bonusRate = $bonusRate > 0 && $bonusRate <= 100 ? $bonusRate : $storeBonusRate;
  233. $bonus = moneyFormat($orderTotal * $bonusRate, 2);
  234. $orderTotal = 0.1;
  235. // 订单数据
  236. $order = [
  237. 'order_no' => $orderNo,
  238. 'user_id' => $userId,
  239. 'store_id' => $storeId,
  240. 'total' => $orderTotal,
  241. 'num' => $orderCount,
  242. 'pay_total' => $orderTotal,
  243. 'receiver_name' => $realname,
  244. 'receiver_mobile' => $mobile,
  245. 'receiver_area' => $area,
  246. 'receiver_address' => $address,
  247. 'bonus' => $bonus,
  248. 'create_time' => time(),
  249. 'update_time' => time(),
  250. 'status' => 1,
  251. 'mark' => 1,
  252. ];
  253. // 订单处理
  254. DB::beginTransaction();
  255. if (!$orderId = $this->model->insertGetId($order)) {
  256. DB::rollBack();
  257. $this->error = '创建订单失败';
  258. RedisService::clear($cacheLockKey);
  259. return false;
  260. }
  261. // 订单商品
  262. if($orderGoods && !OrderGoodsModel::insert($orderGoods)){
  263. DB::rollBack();
  264. $this->error = '处理订单商品错误';
  265. RedisService::clear($cacheLockKey);
  266. return false;
  267. }
  268. // 获取支付参数
  269. /* TODO 支付处理 */
  270. $payOrder = [
  271. 'type' => 1,
  272. 'order_no' => $orderNo,
  273. 'pay_money' => $orderTotal,
  274. 'body' => '购物消费',
  275. 'openid' => $openid
  276. ];
  277. // 调起支付
  278. $payment = PaymentService::make()->minPay($userInfo, $payOrder, 'store');
  279. if (empty($payment)) {
  280. DB::rollBack();
  281. RedisService::clear($cacheLockKey);
  282. $this->error = PaymentService::make()->getError();
  283. return false;
  284. }
  285. // 用户操作记录
  286. DB::commit();
  287. $this->error = '订单创建成功,请前往支付~';
  288. RedisService::clear($cacheLockKey);
  289. return [
  290. 'order_id' => $orderId,
  291. 'payment' => $payment,
  292. 'total' => $payOrder['pay_money'],
  293. 'pay_type' => 10,
  294. ];
  295. }
  296. /**
  297. * 今日数量统计数据
  298. * @param $userId
  299. * @param int $type
  300. * @return array|mixed
  301. */
  302. public function getCountByDay($userId, $status = 3)
  303. {
  304. $cacheKey = "caches:orders:count_day_{$userId}_{$status}";
  305. $data = RedisService::get($cacheKey);
  306. if ($data) {
  307. return $data;
  308. }
  309. $data = $this->model->where(['user_id' => $userId, 'status' => $status, 'mark' => 1])
  310. ->where('create_time', '>=', strtotime(date('Y-m-d')))
  311. ->count('id');
  312. if ($data) {
  313. RedisService::set($cacheKey, $data, rand(5, 10));
  314. }
  315. return $data;
  316. }
  317. /**
  318. * 订单数
  319. * @param $userId
  320. * @param int $status
  321. * @return array|mixed
  322. */
  323. public function getCountByStatus($userId, $status = 3)
  324. {
  325. $cacheKey = "caches:orders:count_status_{$userId}_{$status}";
  326. $data = RedisService::get($cacheKey);
  327. if ($data) {
  328. return $data;
  329. }
  330. $data = $this->model->where(['user_id' => $userId, 'status' => $status, 'mark' => 1])
  331. ->count('id');
  332. if ($data) {
  333. RedisService::set($cacheKey, $data, rand(5, 10));
  334. }
  335. return $data;
  336. }
  337. /**
  338. * 获取订单审核状态
  339. * @param $userId
  340. * @return array|mixed
  341. */
  342. public function checkOrderStatus($userId)
  343. {
  344. $cacheKey = "caches:orders:checkOrder:{$userId}";
  345. $data = RedisService::get($cacheKey);
  346. if ($data) {
  347. return $data;
  348. }
  349. $data = $this->model->with(['confirm'])->where(function ($query) {
  350. $query->where(function ($query) {
  351. $query->where('status', 2)->where('confirm_at', '>=', date('Y-m-d H:i:s', time() - 3600));
  352. })->orWhere(function ($query) {
  353. $query->where('status', 9)->where('confirm_at', '>=', date('Y-m-d H:i:s', time() - 600));
  354. })->orWhere(function ($query) {
  355. $query->where('status', 3)->where('confirm_at', '>=', date('Y-m-d H:i:s', time() - 600));
  356. })->orWhere('status', 1);
  357. })
  358. ->where(['user_id' => $userId, 'mark' => 1])
  359. ->select(['id', 'order_no', 'user_id', 'goods_id', 'status'])
  360. ->orderBy('id', 'desc')
  361. ->first();
  362. $data = $data ? $data->toArray() : [];
  363. $result = [];
  364. if ($data) {
  365. $orderId = isset($data['id']) ? $data['id'] : 0;
  366. $status = isset($data['status']) ? $data['status'] : 0;
  367. $goodsId = isset($data['goods_id']) ? $data['goods_id'] : 0;
  368. $confirmOrder = isset($data['confirm']) ? $data['confirm'] : [];
  369. $confirmOrderId = isset($confirmOrder['id']) ? $confirmOrder['id'] : 0;
  370. $confirmOrderUser = isset($confirmOrder['user']) ? $confirmOrder['user'] : [];
  371. $realname = isset($confirmOrderUser['realname']) ? $confirmOrderUser['realname'] : '';
  372. if ($status == 9) {
  373. $message = "抱歉,订单已被其他师傅接走";
  374. } else if ($status == 2) {
  375. $message = "恭喜您,抢单成功,请前往完成订单!";
  376. } else if ($status == 3) {
  377. $message = "恭喜您,订单已经完成!";
  378. } else {
  379. $pickerCount = $this->model->where(['goods_id' => $goodsId, 'mark' => 1])->whereIn('status', [1, 2])->count('id');
  380. $pickerCount = $pickerCount <= 3 ? 3 : $pickerCount;
  381. $message = "<p style='padding: 5px 0;'>正在抢单</p><p>({$pickerCount}位师傅正在抢单中)</p>";
  382. }
  383. $result = ['order_id' => $orderId, 'goods_id' => $goodsId, 'confirm_order_id' => $confirmOrderId, 'status' => $status, 'message' => $message];
  384. RedisService::set($cacheKey, $result, rand(10, 20));
  385. }
  386. return $result;
  387. }
  388. }