OrderService.php 32 KB

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