OrderService.php 33 KB

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