OrderService.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  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\CartModel;
  13. use App\Models\GoodsModel;
  14. use App\Models\GoodsSkuModel;
  15. use App\Models\MemberModel;
  16. use App\Models\OrderGoodsModel;
  17. use App\Models\OrderModel;
  18. use App\Models\StoreModel;
  19. use App\Services\BaseService;
  20. use App\Services\ConfigService;
  21. use App\Services\Kd100Service;
  22. use App\Services\PaymentService;
  23. use App\Services\RedisService;
  24. use Illuminate\Support\Facades\DB;
  25. /**
  26. * 订单-服务类
  27. * @author laravel开发员
  28. * @since 2020/11/11
  29. * @package App\Services\Api
  30. */
  31. class OrderService extends BaseService
  32. {
  33. // 静态对象
  34. protected static $instance = null;
  35. /**
  36. * 构造函数
  37. * @author laravel开发员
  38. * @since 2020/11/11
  39. */
  40. public function __construct()
  41. {
  42. $this->model = new OrderModel();
  43. }
  44. /**
  45. * 静态入口
  46. */
  47. public static function make()
  48. {
  49. if (!self::$instance) {
  50. self::$instance = new static();
  51. }
  52. return self::$instance;
  53. }
  54. /**
  55. * 订单列表
  56. * @param $params
  57. * @param int $pageSize
  58. * @return array
  59. */
  60. public function getDataList($params, $pageSize = 15)
  61. {
  62. $model = $this->getQuery($params);
  63. // 数据
  64. $list = $model->where(function ($query) use ($params) {
  65. $status = isset($params['status']) ? $params['status'] : 0;
  66. // 进行中
  67. if ($status == 9) {
  68. $query->where('a.refund_status', '>', 0);
  69. } elseif ($status > 0 && is_array($status)) {
  70. $query->whereIn('a.status', $status)->where('a.refund_status', 0);
  71. } else if ($status == 4) {
  72. $query->where('a.status', $status)->where('a.refund_status', 0);
  73. } else if ($status > 0) {
  74. $query->where('a.status', $status)->where('a.refund_status', 0);
  75. }
  76. })->select(['a.*'])
  77. // ->orderBy('a.status', 'asc')
  78. ->orderBy('a.id', 'desc')
  79. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  80. $list = $list ? $list->toArray() : [];
  81. if ($list) {
  82. $statusArr = [1 => '待支付', 2 => '待发货', 3 => '待收货', 4 => '确认收货'];
  83. foreach ($list['data'] as &$item) {
  84. $item['create_time'] = $item['create_time'] ? datetime($item['create_time'], 'Y/m/d H:i') : '';
  85. $status = isset($item['status']) ? $item['status'] : 0;
  86. $item['status_text'] = '待支付';
  87. if ($status) {
  88. $item['status_text'] = isset($statusArr[$status]) ? $statusArr[$status] : '';
  89. }
  90. if ($item['refund_status'] > 0) {
  91. $item['status_text'] = '退款/售后';
  92. }
  93. $item['goods'] = isset($item['goods']) && $item['goods'] ? $item['goods'] : [];
  94. }
  95. unset($item);
  96. }
  97. return [
  98. 'pageSize' => $pageSize,
  99. 'total' => isset($list['total']) ? $list['total'] : 0,
  100. 'list' => isset($list['data']) ? $list['data'] : []
  101. ];
  102. }
  103. /**
  104. * 查询条件
  105. * @param $params
  106. * @return mixed
  107. */
  108. public function getQuery($params)
  109. {
  110. $where = ['a.mark' => 1];
  111. return $this->model->from('orders as a')->with(['orderGoods', 'store'])
  112. ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
  113. ->where($where)
  114. ->where(function ($query) use ($params) {
  115. $userId = isset($params['user_id']) ? intval($params['user_id']) : 0;
  116. if ($userId > 0) {
  117. $query->where('a.user_id', $userId);
  118. }
  119. })
  120. ->where(function ($query) use ($params) {
  121. $keyword = isset($params['keyword']) ? $params['keyword'] : '';
  122. if ($keyword) {
  123. $query->where('a.order_no', 'like', "%{$keyword}%")
  124. ->orWhere('b.mobile', 'like', "%{$keyword}%");
  125. }
  126. });
  127. }
  128. /**
  129. * 订单详情
  130. * @param $id
  131. */
  132. public function getOrderInfo($id, $no='')
  133. {
  134. $where = ['a.order_no'=>$no,'a.id' => $id, 'a.mark' => 1];
  135. if($no){
  136. unset($where['a.id']);
  137. }else{
  138. unset($where['a.order_no']);
  139. }
  140. $statusArr = [1 => '待支付', 2 => '待发货', 3 => '待收货', 4 => '已完成'];
  141. $info = $this->model->from('orders as a')
  142. ->with(['orderGoods','store'])
  143. ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
  144. ->where($where)
  145. ->select(['a.*'])
  146. ->first();
  147. if ($info) {
  148. $info = $info->toArray();
  149. $info['create_time'] = $info['create_time'] ? datetime($info['create_time'], 'Y-m-d H:i:s') : '';
  150. $info['pay_at'] = $info['pay_at'] ? datetime(strtotime($info['pay_at']), 'Y-m-d H:i:s') : '';
  151. $info['receiver_mobile_text'] = $info['receiver_mobile']? format_mobile($info['receiver_mobile']):'';
  152. $status = isset($info['status']) ? $info['status'] : 0;
  153. $info['status_text'] = '待支付';
  154. if ($status) {
  155. $info['status_text'] = isset($statusArr[$status]) ? $statusArr[$status] : '';
  156. }
  157. }
  158. return $info;
  159. }
  160. /**
  161. * 创建订单
  162. * @param $userId 用户
  163. * @param $params 参数
  164. * @return array|false
  165. */
  166. public function createOrder($userId, $params)
  167. {
  168. $submitType = isset($params['type']) && $params['type'] ? $params['type'] : '';
  169. $addressId = isset($params['address_id']) && $params['address_id'] ? $params['address_id'] : 0;
  170. $goods = isset($params['goods']) && $params['goods'] ? $params['goods'] : [];
  171. $ids = $goods ? array_column($goods, 'id') : [];
  172. $skuIds = $goods ? array_column($goods, 'sku_id') : [];
  173. // 参数验证
  174. if (empty($goods) || empty($ids)) {
  175. $this->error = '商品参数不为空';
  176. return false;
  177. }
  178. if ($addressId <= 0) {
  179. $this->error = '请选择收货地址';
  180. return false;
  181. }
  182. // 缓存锁
  183. $cacheLockKey = "caches:orders:submit_lock:{$userId}";
  184. if (RedisService::get($cacheLockKey)) {
  185. $this->error = '订单处理中~';
  186. return false;
  187. }
  188. // 商品数据
  189. $orderNo = get_order_num('GX');
  190. RedisService::set($cacheLockKey, ['params' => $params, 'user_id' => $userId], rand(3, 5));
  191. $result = GoodsService::make()->getOrderGoods($ids, $goods, $orderNo, $userId);
  192. if (empty($result)) {
  193. RedisService::clear($cacheLockKey);
  194. $this->error = GoodsService::make()->getError();
  195. return false;
  196. }
  197. $orderGoods = isset($result['goods']) ? $result['goods'] : [];
  198. $orderTotal = isset($result['total']) ? $result['total'] : 0;
  199. $orderCount = isset($result['count']) ? $result['count'] : 0;
  200. $storeId = isset($result['store_id']) ? $result['store_id'] : 0;
  201. if (empty($orderGoods)) {
  202. RedisService::clear($cacheLockKey);
  203. $this->error = '获取订单商品错误~';
  204. return false;
  205. }
  206. if ($orderTotal <= 0) {
  207. RedisService::clear($cacheLockKey);
  208. $this->error = '订单金额错误~';
  209. return false;
  210. }
  211. if ($orderCount <= 0) {
  212. RedisService::clear($cacheLockKey);
  213. $this->error = '订单商品数量错误~';
  214. return false;
  215. }
  216. $system = isset($params['system']) && $params['system'] ? $params['system'] : [];
  217. $platform = isset($system['platform']) && $system['platform']? $system['platform'] : 'mp';
  218. // 用户信息
  219. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  220. ->select(['id', 'openid','wechat_openid', 'mobile', 'nickname', 'realname', 'balance', 'status'])
  221. ->first();
  222. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  223. $openid = isset($userInfo['openid']) ? $userInfo['openid'] : '';
  224. $wechatOpenid = isset($userInfo['wechat_openid']) &&$userInfo['wechat_openid'] ? $userInfo['wechat_openid'] : $openid;
  225. $openid = $platform=='wechat'?$wechatOpenid:$openid;
  226. if (empty($userInfo) || $status != 1) {
  227. $this->error = 1045;
  228. RedisService::clear($cacheLockKey);
  229. return false;
  230. }
  231. if (empty($openid)) {
  232. $this->error = '用户微信未授权,请重新授权登录';
  233. RedisService::clear($cacheLockKey);
  234. return false;
  235. }
  236. // 收货地址信息
  237. $addressInfo = MemberAddressService::make()->getBindInfo($userId, $addressId);
  238. $realname = isset($addressInfo['realname']) ? $addressInfo['realname'] : '';
  239. $mobile = isset($addressInfo['mobile']) ? $addressInfo['mobile'] : '';
  240. $area = isset($addressInfo['area']) ? $addressInfo['area'] : '';
  241. $address = isset($addressInfo['address']) ? $addressInfo['address'] : '';
  242. if (empty($addressInfo) || empty($realname) || empty($mobile) || empty($area) || empty($address)) {
  243. RedisService::clear($cacheLockKey);
  244. $this->error = '收货地址信息错误,请核对后重试~';
  245. return false;
  246. }
  247. // 商家佣金
  248. $storeInfo = StoreModel::where(['id' => $storeId])->first();
  249. $bonusRate = isset($storeInfo['bonus_rate']) ? floatval($storeInfo['bonus_rate']) : 0;
  250. $storeBonusRate = ConfigService::make()->getConfigByCode('store_bonus_rate', 0);
  251. $storeBonusRate = $storeBonusRate > 0 && $storeBonusRate <= 100 ? $storeBonusRate : 0;
  252. $bonusRate = $bonusRate > 0 && $bonusRate <= 100 ? $bonusRate : $storeBonusRate;
  253. $bonus = moneyFormat($orderTotal * $bonusRate / 100, 2);
  254. $total = $orderTotal;
  255. if (env('PAY_DEBUG')) {
  256. $orderTotal = 0.1;
  257. }
  258. // 订单数据
  259. $order = [
  260. 'order_no' => $orderNo,
  261. 'user_id' => $userId,
  262. 'store_id' => $storeId,
  263. 'total' => $total,
  264. 'num' => $orderCount,
  265. 'pay_total' => $orderTotal,
  266. 'receiver_name' => $realname,
  267. 'receiver_mobile' => $mobile,
  268. 'receiver_area' => $area,
  269. 'receiver_address' => $address,
  270. 'bonus' => $bonus,
  271. 'create_time' => time(),
  272. 'update_time' => time(),
  273. 'status' => 1,
  274. 'mark' => 1,
  275. ];
  276. // 订单处理
  277. DB::beginTransaction();
  278. if (!$orderId = $this->model->insertGetId($order)) {
  279. DB::rollBack();
  280. $this->error = '创建订单失败';
  281. RedisService::clear($cacheLockKey);
  282. return false;
  283. }
  284. // 订单商品
  285. if ($orderGoods && !OrderGoodsModel::insert($orderGoods)) {
  286. DB::rollBack();
  287. $this->error = '处理订单商品错误';
  288. RedisService::clear($cacheLockKey);
  289. return false;
  290. }
  291. // 获取支付参数
  292. /* TODO 支付处理 */
  293. $payOrder = [
  294. 'type' => 1,
  295. 'order_no' => $orderNo,
  296. 'pay_money' => $orderTotal,
  297. 'body' => '购物消费',
  298. 'openid' => $openid
  299. ];
  300. // 调起支付
  301. if($platform == 'wechat'){
  302. $payment = PaymentService::make()->mpPay($userInfo, $payOrder, 'store');
  303. }else{
  304. $payment = PaymentService::make()->minPay($userInfo, $payOrder, 'store');
  305. }
  306. if (empty($payment)) {
  307. DB::rollBack();
  308. RedisService::clear($cacheLockKey);
  309. $this->error = PaymentService::make()->getError();
  310. return false;
  311. }
  312. // 商品库存扣除
  313. if($orderGoods){
  314. foreach($orderGoods as $goods){
  315. $id = isset($goods['goods_id'])?$goods['goods_id']:0;
  316. $num = isset($goods['num'])?$goods['num']:0;
  317. $skuId = isset($goods['sku_id'])?$goods['sku_id']:0;
  318. if($id && !GoodsModel::where(['id'=>$id])->update(['stock'=>DB::raw("stock - {$num}"),'update_time'=>time()])){
  319. DB::rollBack();
  320. RedisService::clear($cacheLockKey);
  321. $this->error = '商品库存处理失败';
  322. return false;
  323. }
  324. if($skuId && !GoodsSkuModel::where(['id'=>$skuId])->update(['stock'=>DB::raw("stock - {$num}"),'update_time'=>time()])){
  325. DB::rollBack();
  326. RedisService::clear($cacheLockKey);
  327. $this->error = '商品库存处理失败';
  328. return false;
  329. }
  330. }
  331. }
  332. // 清空购物车结算商品
  333. if($submitType == 'cart'){
  334. CartModel::whereIn('goods_id',$ids)->whereIn('sku_id',$skuIds)->where(['user_id'=>$userId,'mark'=>1])->update(['mark'=>0,'num'=>0,'update_time'=>time()]);
  335. RedisService::clear("caches:goods:cartCount:{$userId}");
  336. }
  337. // 用户操作记录
  338. DB::commit();
  339. $this->error = '订单创建成功,请前往支付~';
  340. RedisService::clear($cacheLockKey);
  341. return [
  342. 'order_id' => $orderId,
  343. 'payment' => $payment,
  344. 'total' => $payOrder['pay_money'],
  345. 'pay_type' => 10,
  346. ];
  347. }
  348. /**
  349. * 订单支付
  350. * @param $userId
  351. * @param $id
  352. * @return array|false
  353. */
  354. public function pay($userId, $id)
  355. {
  356. if ($id <= 0) {
  357. $this->error = '请选择支付订单';
  358. return false;
  359. }
  360. // 缓存锁
  361. $cacheLockKey = "caches:orders:pay_lock:{$userId}_{$id}";
  362. if (RedisService::get($cacheLockKey)) {
  363. $this->error = '订单处理中~';
  364. return false;
  365. }
  366. // 商品数据
  367. RedisService::set($cacheLockKey, ['order_id' => $id, 'user_id' => $userId], rand(3, 5));
  368. // 用户信息
  369. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  370. ->select(['id', 'openid', 'mobile', 'nickname', 'realname', 'balance', 'status'])
  371. ->first();
  372. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  373. $openid = isset($userInfo['openid']) ? $userInfo['openid'] : '';
  374. if (empty($userInfo) || $status != 1) {
  375. $this->error = 1045;
  376. RedisService::clear($cacheLockKey);
  377. return false;
  378. }
  379. if (empty($openid)) {
  380. $this->error = '用户微信未授权,请重新授权登录';
  381. RedisService::clear($cacheLockKey);
  382. return false;
  383. }
  384. // 订单信息
  385. $info = $this->model->where(['id' => $id, 'mark' => 1])
  386. ->select(['id', 'order_no', 'pay_total', 'status'])
  387. ->first();
  388. $orderTotal = isset($info['pay_total']) ? $info['pay_total'] : 0;
  389. $orderNo = isset($info['order_no']) ? $info['order_no'] : '';
  390. $status = isset($info['status']) ? $info['status'] : 0;
  391. if (empty($info) || empty($orderNo)) {
  392. $this->error = '订单信息不存在';
  393. RedisService::clear($cacheLockKey);
  394. return false;
  395. }
  396. if ($status != 1) {
  397. $this->error = '订单已支付';
  398. RedisService::clear($cacheLockKey);
  399. return false;
  400. }
  401. // 获取支付参数
  402. /* TODO 支付处理 */
  403. $payOrder = [
  404. 'type' => 1,
  405. 'order_no' => $orderNo,
  406. 'pay_money' => $orderTotal,
  407. 'body' => '购物消费',
  408. 'openid' => $openid
  409. ];
  410. // 调起支付
  411. $payment = PaymentService::make()->minPay($userInfo, $payOrder, 'store');
  412. if (empty($payment)) {
  413. DB::rollBack();
  414. RedisService::clear($cacheLockKey);
  415. $this->error = PaymentService::make()->getError();
  416. return false;
  417. }
  418. // 用户操作记录
  419. DB::commit();
  420. $this->error = '支付请求成功,请前往支付~';
  421. RedisService::clear($cacheLockKey);
  422. return [
  423. 'order_id' => $id,
  424. 'payment' => $payment,
  425. 'total' => $payOrder['pay_money'],
  426. 'pay_type' => 10,
  427. ];
  428. }
  429. /**
  430. * 订单取消
  431. * @param $userId
  432. * @param $orderId
  433. * @return array|false
  434. */
  435. public function cancel($userId, $orderId)
  436. {
  437. if ($orderId <= 0) {
  438. $this->error = '请选择订单';
  439. return false;
  440. }
  441. // 缓存锁
  442. $cacheLockKey = "caches:orders:cancel_lock:{$userId}_{$orderId}";
  443. if (RedisService::get($cacheLockKey)) {
  444. $this->error = '订单处理中~';
  445. return false;
  446. }
  447. // 商品数据
  448. RedisService::set($cacheLockKey, ['order_id' => $orderId, 'user_id' => $userId], rand(3, 5));
  449. // 用户信息
  450. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  451. ->select(['id', 'openid', 'mobile', 'nickname', 'realname', 'balance', 'status'])
  452. ->first();
  453. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  454. if (empty($userInfo) || $status != 1) {
  455. $this->error = 1045;
  456. RedisService::clear($cacheLockKey);
  457. return false;
  458. }
  459. // 订单信息
  460. $info = $this->model->where(['id' => $orderId, 'mark' => 1])
  461. ->select(['id', 'order_no', 'pay_total', 'status'])
  462. ->first();
  463. $orderNo = isset($info['order_no']) ? $info['order_no'] : '';
  464. $status = isset($info['status']) ? $info['status'] : 0;
  465. if (empty($info) || empty($orderNo)) {
  466. $this->error = '订单信息不存在';
  467. RedisService::clear($cacheLockKey);
  468. return false;
  469. }
  470. if ($status != 1) {
  471. $this->error = '订单已支付';
  472. RedisService::clear($cacheLockKey);
  473. return false;
  474. }
  475. $orderGoods = OrderGoodsModel::where(['order_no'=> $orderNo,'mark'=>1])
  476. ->select(['goods_id','num','sku_id'])
  477. ->get();
  478. DB::beginTransaction();
  479. if($orderGoods){
  480. foreach($orderGoods as $goods){
  481. $goodsId = isset($goods['goods_id'])?$goods['goods_id']:0;
  482. $num = isset($goods['num'])?$goods['num']:0;
  483. $skuId = isset($goods['sku_id'])?$goods['sku_id']:0;
  484. if($goodsId && !GoodsModel::where(['id'=>$goodsId])->update(['stock'=>DB::raw("stock + {$num}"),'update_time'=>time()])){
  485. DB::rollBack();
  486. RedisService::clear($cacheLockKey);
  487. $this->error = '商品库存处理失败';
  488. return false;
  489. }
  490. if($skuId && !GoodsSkuModel::where(['id'=>$skuId])->update(['stock'=>DB::raw("stock + {$num}"),'update_time'=>time()])){
  491. DB::rollBack();
  492. RedisService::clear($cacheLockKey);
  493. $this->error = '商品库存处理失败';
  494. return false;
  495. }
  496. }
  497. }
  498. $this->error = '取消订单成功';
  499. $this->model->where(['user_id' => $userId, 'mark' => 0])->where('update_time', '<=', time() - 300)->delete();
  500. OrderGoodsModel::where(['order_no' => $orderNo, 'mark' => 0])->where('update_time', '<=', time() - 300)->delete();
  501. $this->model->where(['id' => $orderId])->update(['mark' => 0, 'update_time' => time()]);
  502. OrderGoodsModel::where(['order_no' => $orderNo])->update(['mark' => 0, 'update_time' => time()]);
  503. DB::commit();
  504. return ['id' => $orderId];
  505. }
  506. /**
  507. * 订单完成
  508. * @param $userId 订单用户ID
  509. * @param $id 订单ID
  510. * @return array|false
  511. */
  512. public function complete($userId, $id, $check= true)
  513. {
  514. if ($id <= 0) {
  515. $this->error = '请选择订单';
  516. return false;
  517. }
  518. // 缓存锁
  519. $cacheLockKey = "caches:orders:complete_lock:{$userId}_{$id}";
  520. if (RedisService::get($cacheLockKey)) {
  521. $this->error = '订单处理中~';
  522. return false;
  523. }
  524. // 商品数据
  525. RedisService::set($cacheLockKey, ['order_id' => $id, 'user_id' => $userId], rand(3, 5));
  526. // 用户信息
  527. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  528. ->select(['id', 'openid', 'mobile', 'parent_id', 'nickname', 'realname', 'balance', 'status'])
  529. ->first();
  530. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  531. $parentId = isset($userInfo['parent_id']) ? $userInfo['parent_id'] : 0;
  532. if ($check && (empty($userInfo) || $status != 1)) {
  533. $this->error = 1045;
  534. RedisService::clear($cacheLockKey);
  535. return false;
  536. }
  537. // 订单信息
  538. $info = $this->model->with(['orderGoods'])->where(['id' => $id, 'mark' => 1])
  539. ->select(['id', 'order_no', 'store_id', 'pay_total', 'bonus', 'delivery_no', 'delivery_company', 'delivery_code', 'status'])
  540. ->first();
  541. $orderNo = isset($info['order_no']) ? $info['order_no'] : '';
  542. $deliveryNo = isset($info['delivery_no']) ? $info['delivery_no'] : '';
  543. $deliverCompany = isset($info['delivery_company']) ? $info['delivery_company'] : '';
  544. $storeId = isset($info['store_id']) ? $info['store_id'] : 0;
  545. $orderTotal = isset($info['pay_total']) ? $info['pay_total'] : 0;
  546. $bonus = isset($info['bonus']) ? $info['bonus'] : 0;
  547. $status = isset($info['status']) ? $info['status'] : 0;
  548. $orderGoods = isset($info['order_goods']) ? $info['order_goods'] : [];
  549. if (empty($info) || empty($orderNo)) {
  550. $this->error = '订单信息不存在';
  551. RedisService::clear($cacheLockKey);
  552. return false;
  553. }
  554. if ($status != 3) {
  555. $this->error = '订单未发货';
  556. RedisService::clear($cacheLockKey);
  557. return false;
  558. }
  559. if (empty($deliveryNo) || empty($deliverCompany)) {
  560. $this->error = '订单发货信息错误,请联系客服';
  561. $this->model->where(['id'=>$id])->update(['is_complete'=>1,'complete_remark'=>$this->error]);
  562. RedisService::clear("caches:orders:completeList");
  563. RedisService::clear($cacheLockKey);
  564. return false;
  565. }
  566. DB::beginTransaction();
  567. $updateData = ['status' => 4, 'update_time' => time()];
  568. if(!$check){
  569. $updateData['is_complete'] = 1;
  570. $updateData['complete_remark'] = '自动收货';
  571. }
  572. $this->model->where(['id' => $id])->update($updateData);
  573. // 商家订单数据统计
  574. $updateData = ['order_count' => DB::raw('order_count+1'), 'order_total' => DB::raw("order_total + {$orderTotal}")];
  575. StoreModel::where(['id' => $storeId])->update($updateData);
  576. // 商品销量数据
  577. if ($orderGoods) {
  578. $counts = [];
  579. foreach ($orderGoods as $item) {
  580. $counts[$item['goods_id']] = isset($counts[$item['goods_id']]) ? $counts[$item['goods_id']] : 0;
  581. $counts[$item['goods_id']] += $item['num'];
  582. }
  583. if ($counts) {
  584. foreach ($counts as $id => $v) {
  585. GoodsModel::where(['id' => $id])->update(['sales' => DB::raw("sales + {$v}"), 'update_time' => time()]);
  586. }
  587. }
  588. }
  589. // 结算商家收益
  590. if (SettleService::make()->storeBonus($storeId, $bonus, $info) < 0) {
  591. DB::rollBack();
  592. $this->error = SettleService::make()->getError();
  593. RedisService::clear($cacheLockKey);
  594. return false;
  595. }
  596. // 代理佣金结算
  597. if (SettleService::make()->agentBonus($userId, $orderTotal, $info, $parentId) < 0) {
  598. DB::rollBack();
  599. $this->error = SettleService::make()->getError();
  600. RedisService::clear($cacheLockKey);
  601. return false;
  602. }
  603. DB::commit();
  604. $this->error = '确认收货成功';
  605. RedisService::clear("caches:orders:completeList");
  606. return ['id' => $id,'msg'=>$this->error];
  607. }
  608. /**
  609. * 售后或退款
  610. * @param $userId
  611. * @param $params
  612. * @return array|false
  613. */
  614. public function after($userId, $params)
  615. {
  616. $id = isset($params['id']) ? $params['id'] : 0;
  617. $afterType = isset($params['after_type']) ? $params['after_type'] : 1;
  618. if ($id <= 0) {
  619. $this->error = '请选择订单';
  620. return false;
  621. }
  622. // 缓存锁
  623. $cacheLockKey = "caches:orders:after_lock:{$userId}_{$id}";
  624. if (RedisService::get($cacheLockKey)) {
  625. $this->error = '订单处理中~';
  626. return false;
  627. }
  628. // 商品数据
  629. RedisService::set($cacheLockKey, ['params' => $params, 'user_id' => $userId], rand(3, 5));
  630. // 用户信息
  631. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  632. ->select(['id', 'openid', 'mobile', 'nickname', 'realname', 'balance', 'status'])
  633. ->first();
  634. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  635. if (empty($userInfo) || $status != 1) {
  636. $this->error = 1045;
  637. RedisService::clear($cacheLockKey);
  638. return false;
  639. }
  640. // 订单信息
  641. $info = $this->model->where(['id' => $id, 'mark' => 1])
  642. ->select(['id', 'order_no', 'after_type', 'refund_status', 'pay_total', 'status'])
  643. ->first();
  644. $orderNo = isset($info['order_no']) ? $info['order_no'] : '';
  645. $status = isset($info['status']) ? $info['status'] : 0;
  646. $refundStatus = isset($info['refund_status']) ? $info['refund_status'] : 0;
  647. if (empty($info) || empty($orderNo)) {
  648. $this->error = '订单信息不存在';
  649. RedisService::clear($cacheLockKey);
  650. return false;
  651. }
  652. if ($status == 1) {
  653. $this->error = '订单未支付';
  654. RedisService::clear($cacheLockKey);
  655. return false;
  656. }
  657. if ($status == 4 && $afterType==2) {
  658. $this->error = '订单已完成';
  659. RedisService::clear($cacheLockKey);
  660. return false;
  661. }
  662. if ($refundStatus > 0 && $refundStatus != 4) {
  663. $this->error = '订单售后处理中';
  664. RedisService::clear($cacheLockKey);
  665. return false;
  666. }
  667. $afterRealname = isset($params['after_realname']) ? $params['after_realname'] : '';
  668. $afterPhone = isset($params['after_phone']) ? $params['after_phone'] : '';
  669. $afterRemark = isset($params['after_remark']) ? $params['after_remark'] : '';
  670. if ($afterType == 1) {
  671. if (empty($afterRealname) || empty($afterPhone) || empty($afterRemark)) {
  672. $this->error = '请填写售后信息';
  673. RedisService::clear($cacheLockKey);
  674. return false;
  675. }
  676. }
  677. $data = [
  678. 'after_type' => $afterType,
  679. 'after_realname' => $afterRealname,
  680. 'after_phone' => $afterPhone,
  681. 'after_remark' => $afterRemark,
  682. 'refund_remark' => isset($params['refund_remark']) ? $params['refund_remark'] : '',
  683. 'refund_status' => 3,
  684. 'update_time' => time()
  685. ];
  686. $this->model->where(['id' => $id])->update($data);
  687. $this->error = '订单申请售后成功';
  688. return ['id' => $id];
  689. }
  690. /**
  691. * 今日数量统计数据
  692. * @param $userId
  693. * @param int $type
  694. * @return array|mixed
  695. */
  696. public function getCountByDay($userId, $status = 3)
  697. {
  698. $cacheKey = "caches:orders:count_day_{$userId}_{$status}";
  699. $data = RedisService::get($cacheKey);
  700. if ($data) {
  701. return $data;
  702. }
  703. $data = $this->model->where(['user_id' => $userId, 'status' => $status, 'mark' => 1])
  704. ->where('create_time', '>=', strtotime(date('Y-m-d')))
  705. ->count('id');
  706. if ($data) {
  707. RedisService::set($cacheKey, $data, rand(5, 10));
  708. }
  709. return $data;
  710. }
  711. /**
  712. * 订单数
  713. * @param $userId
  714. * @param int $status
  715. * @return array|mixed
  716. */
  717. public function getCountByStatus($userId, $status = 3)
  718. {
  719. $cacheKey = "caches:orders:count_status_{$userId}_{$status}";
  720. $data = RedisService::get($cacheKey);
  721. if ($data) {
  722. return $data;
  723. }
  724. $data = $this->model->where(['user_id' => $userId, 'status' => $status, 'mark' => 1])
  725. ->count('id');
  726. if ($data) {
  727. RedisService::set($cacheKey, $data, rand(5, 10));
  728. }
  729. return $data;
  730. }
  731. /**
  732. * 物流查询
  733. * @param $id
  734. * @return array|false|mixed
  735. */
  736. public function getDelivery($id)
  737. {
  738. $info = $this->model->where(['id' => $id, 'mark' => 1])->first();
  739. $deliveryNo = isset($info['delivery_no']) ? $info['delivery_no'] : '';
  740. $deliveryCode = isset($info['delivery_code']) ? $info['delivery_code'] : '';
  741. $mobile = isset($info['receiver_mobile']) ? $info['receiver_mobile'] : '';
  742. $receiverArea = isset($info['receiver_area']) && $info['receiver_area']? $info['receiver_area'] : '';
  743. if (empty($info)) {
  744. $this->error = '请选择订单';
  745. return false;
  746. }
  747. $cacheKey = "caches:kd100:order_{$id}";
  748. $data = RedisService::get($cacheKey);
  749. if ($data) {
  750. return $data;
  751. }
  752. $result = Kd100Service::make()->query($deliveryNo, $mobile, $deliveryCode,$receiverArea);
  753. RedisService::set($cacheKey.'_result', $result, 300);
  754. $status = isset($result['status'])?$result['status']:0;
  755. $data = isset($result['data'])?$result['data']:[];
  756. $courierInfo = isset($result['courierInfo'])?$result['courierInfo']:[];
  757. $arrivalTime = isset($result['arrivalTime'])?$result['arrivalTime']:'';
  758. $predictedRoute = isset($result['predictedRoute'])?$result['predictedRoute']:[];
  759. $predictedData = $predictedRoute?end($predictedRoute):[];
  760. $arrivalData = [];
  761. if($arrivalTime){
  762. $arrivalData['arrivalTime'] = dayFormat(strtotime($arrivalTime.':00:00'));
  763. $arrivalData['predictedData'] = $predictedData;
  764. }
  765. if($courierInfo && $courierInfo['deliveryManPhone']){
  766. $courierInfo['deliveryManPhone'] = explode(',', $courierInfo['deliveryManPhone']);
  767. $courierInfo['deliveryPhone'] = $courierInfo['deliveryManPhone'][1]?$courierInfo['deliveryManPhone'][1]:$courierInfo['deliveryManPhone'][0];
  768. }
  769. if ($data && $status==200) {
  770. RedisService::set($cacheKey, ['info'=>$courierInfo,'arrivalData'=>$arrivalData,'list'=>$data], 1200);
  771. }
  772. return $data?['info'=>$courierInfo,'arrivalData'=>$arrivalData,'list'=>$data]:[];
  773. }
  774. /**
  775. * 已发货待完成订单
  776. * @return array|mixed
  777. */
  778. public function getCompleteOrders()
  779. {
  780. $cacheKey = "caches:orders:completeList";
  781. $datas = RedisService::get($cacheKey);
  782. if($datas){
  783. return $datas;
  784. }
  785. $completeDay = ConfigService::make()->getConfigByCode('order_complete_day',7);
  786. $limitNum = ConfigService::make()->getConfigByCode('order_complete_batch_num',300);
  787. $limitNum = $limitNum>10 && $limitNum<2000? $limitNum : 300;
  788. $completeDay = $completeDay>=1 && $completeDay<30? $completeDay : 7;
  789. $datas = $this->model->where(['status'=>3,'is_complete'=>2,'mark'=>1])
  790. ->whereNotNull('delivery_no')
  791. ->select(['id','user_id','order_no','status'])
  792. ->where('pay_at','<=', date('Y-m-d H:i:s', time() - $completeDay * 86400))
  793. ->limit($limitNum)
  794. ->get();
  795. $datas = $datas?$datas->toArray() : [];
  796. if($datas){
  797. RedisService::set($cacheKey, $datas, rand(300, 600));
  798. }
  799. return $datas;
  800. }
  801. }