OrderService.php 35 KB

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