OrderService.php 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  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\AccountLogModel;
  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. if ($status > 0 && is_array($status)) {
  67. $query->whereIn('a.status', $status)->where('a.refund_status', 0);
  68. } else if ($status == 6) {
  69. $query->where('a.status', '>', 1)->where('a.refund_status', '>', 0);
  70. } else if ($status > 0) {
  71. $query->where('a.status', $status)->where('a.refund_status', 0);
  72. }
  73. })->select(['a.*'])
  74. ->orderBy('a.id', 'desc')
  75. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  76. $list = $list ? $list->toArray() : [];
  77. if ($list) {
  78. $statusArr = [1 => '待支付', 2 => '待发货', 3 => '待收货', 4 => '确认收货'];
  79. foreach ($list['data'] as &$item) {
  80. $item['create_time'] = $item['create_time'] ? dateFormat(strtotime($item['create_time']), 'Y-m-d') : '';
  81. $status = isset($item['status']) ? $item['status'] : 0;
  82. $item['status_text'] = '待支付';
  83. if ($status) {
  84. $item['status_text'] = isset($statusArr[$status]) ? $statusArr[$status] : '';
  85. }
  86. if ($item['refund_status'] > 0) {
  87. $item['status_text'] = '退款/售后';
  88. }
  89. $item['goods'] = isset($item['goods']) && $item['goods'] ? $item['goods'] : [];
  90. $item['real_total'] = $item['pay_total'];
  91. $item['pay_total'] = moneyFormat($item['pay_total'] + $item['delivery_fee'], 2);
  92. }
  93. unset($item);
  94. }
  95. return [
  96. 'pageSize' => $pageSize,
  97. 'total' => isset($list['total']) ? $list['total'] : 0,
  98. 'list' => isset($list['data']) ? $list['data'] : []
  99. ];
  100. }
  101. /**
  102. * 查询条件
  103. * @param $params
  104. * @return mixed
  105. */
  106. public function getQuery($params)
  107. {
  108. $where = ['a.is_hide' => 0,'a.main_no'=>'', 'a.mark' => 1];
  109. return $this->model->from('orders as a')
  110. ->with(['orderGoods', 'store'])
  111. ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
  112. ->where($where)
  113. ->where(function ($query) use ($params) {
  114. $userId = isset($params['user_id']) ? intval($params['user_id']) : 0;
  115. if ($userId > 0) {
  116. $query->where('a.user_id', $userId);
  117. }
  118. // 订单类型
  119. $type = isset($params['type']) ? intval($params['type']) : 0;
  120. if ($type > 0) {
  121. $query->where('a.type', $type);
  122. }
  123. })
  124. ->where(function ($query) use ($params) {
  125. $keyword = isset($params['keyword']) ? $params['keyword'] : '';
  126. if ($keyword) {
  127. $query->where('a.order_no', 'like', "%{$keyword}%")
  128. ->orWhere('b.mobile', 'like', "%{$keyword}%");
  129. }
  130. });
  131. }
  132. /**
  133. * 订单详情
  134. * @param $id
  135. */
  136. public function getOrderInfo($id, $no = '')
  137. {
  138. $where = ['a.order_no' => $no, 'a.id' => $id, 'a.mark' => 1];
  139. if ($no) {
  140. unset($where['a.id']);
  141. } else {
  142. unset($where['a.order_no']);
  143. }
  144. $statusArr = [1 => '待支付', 2 => '待发货', 3 => '待收货', 4 => '已完成'];
  145. $info = $this->model->from('orders as a')
  146. ->with(['orderGoods', 'store'])
  147. ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
  148. ->where($where)
  149. ->select(['a.*'])
  150. ->first();
  151. if ($info) {
  152. $info = $info->toArray();
  153. $info['create_time'] = $info['create_time'] ? datetime($info['create_time'], 'Y-m-d H:i:s') : '';
  154. $info['pay_at'] = $info['pay_at'] ? datetime(strtotime($info['pay_at']), 'Y-m-d H:i:s') : '';
  155. $info['receiver_mobile_text'] = $info['receiver_mobile'] ? format_mobile($info['receiver_mobile']) : '';
  156. $info['real_total'] = $info['pay_total'];
  157. $info['pay_total'] = moneyFormat($info['pay_total'] + $info['delivery_fee'], 2);
  158. $status = isset($info['status']) ? $info['status'] : 0;
  159. $info['status_text'] = '待支付';
  160. if ($status) {
  161. $info['status_text'] = isset($statusArr[$status]) ? $statusArr[$status] : '';
  162. }
  163. }
  164. return $info;
  165. }
  166. /**
  167. * 创建订单
  168. * @param $userId 用户
  169. * @param $params 参数
  170. * @return array|false
  171. */
  172. public function createOrder($userId, $params)
  173. {
  174. $type = isset($params['type']) && $params['type'] ? $params['type'] : 1;
  175. $addressId = isset($params['address_id']) && $params['address_id'] ? $params['address_id'] : 0;
  176. $goods = isset($params['goods']) && $params['goods'] ? $params['goods'] : [];
  177. $ids = $goods ? array_column($goods, 'id') : [];
  178. // 参数验证
  179. if (empty($goods) || empty($ids)) {
  180. $this->error = '商品参数不为空';
  181. return false;
  182. }
  183. if ($addressId <= 0) {
  184. $this->error = '请选择收货地址';
  185. return false;
  186. }
  187. // 缓存锁
  188. $cacheLockKey = "caches:orders:submit_lock:{$userId}";
  189. if (RedisService::get($cacheLockKey)) {
  190. $this->error = '订单处理中~';
  191. return false;
  192. }
  193. // 用户信息
  194. RedisService::set($cacheLockKey, ['params' => $params, 'user_id' => $userId], rand(3, 5));
  195. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  196. ->select(['id', 'openid','nickname','member_level','parent_id','point_id','points', 'buy_type','property','balance', 'bd_score', 'status'])
  197. ->first();
  198. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  199. $openid = isset($userInfo['openid']) ? $userInfo['openid'] : 0;
  200. $buyType = isset($userInfo['buy_type']) ? $userInfo['buy_type'] : 0;
  201. $bdScore = isset($userInfo['bd_score']) ? $userInfo['bd_score'] : 0;
  202. $discountPoint = isset($userInfo['discount_point']) ? $userInfo['discount_point'] : 0; // 折扣
  203. if (empty($userInfo) || $status != 1) {
  204. $this->error = 1045;
  205. return false;
  206. }
  207. if (empty($openid)) {
  208. $this->error = 1042;
  209. return false;
  210. }
  211. // 商品数据
  212. $orderNo = get_order_num('JK');
  213. $result = GoodsService::make()->getOrderGoods($ids, $goods, $userId, $orderNo, $discountPoint);
  214. if (empty($result)) {
  215. RedisService::clear($cacheLockKey);
  216. $this->error = GoodsService::make()->getError();
  217. return false;
  218. }
  219. $orderGoods = isset($result['goods']) ? $result['goods'] : [];
  220. $goodsTotal = isset($result['goods_total']) ? $result['goods_total'] : 0; // 商品总价
  221. $orderTotal = isset($result['order_total']) ? $result['order_total'] : 0; // 订单结算金额(折后)
  222. $bdScoreTotal = isset($result['bd_score_total']) ? $result['bd_score_total'] : 0; // 报单积分
  223. $profitTotal = isset($result['profit_total']) ? $result['profit_total'] : 0; // 利润
  224. $discountTotal = isset($result['discount_total']) ? $result['discount_total'] : 0; // 折扣金额
  225. $orderCount = isset($result['count']) ? $result['count'] : 0;
  226. $deliveryFee = isset($result['delivery_fee']) ? $result['delivery_fee'] : 0; // 运费
  227. $storeId = isset($result['store_id']) ? $result['store_id'] : 0; // 企业/商家
  228. if (empty($orderGoods)) {
  229. RedisService::clear($cacheLockKey);
  230. $this->error = '获取订单商品错误~';
  231. return false;
  232. }
  233. if ($orderTotal <= 0) {
  234. RedisService::clear($cacheLockKey);
  235. $this->error = '订单金额错误~';
  236. return false;
  237. }
  238. if ($orderCount <= 0) {
  239. RedisService::clear($cacheLockKey);
  240. $this->error = '订单商品数量错误~';
  241. return false;
  242. }
  243. // 创业大礼包
  244. $mealId = 0;
  245. if ($type == 2) {
  246. $mealId = isset($ids[0]) ? $ids[0] : 0;
  247. if ($buyType != $mealId) {
  248. RedisService::clear($cacheLockKey);
  249. $this->error = '该礼包您暂时不满足购买条件';
  250. return false;
  251. }
  252. // 报单积分是否够
  253. if ($bdScore < $bdScoreTotal) {
  254. RedisService::clear($cacheLockKey);
  255. $this->error = '抱歉,您的报单积分不足';
  256. return false;
  257. }
  258. // 是否购买过
  259. $buyLimit = ConfigService::make()->getConfigByCode('business_buy_limit', 0);
  260. $buyLimit = $buyLimit>0?$buyLimit:0;
  261. if($buyLimit>0){
  262. $checkOrderCount = $this->checkBusinessOrder($userId, $mealId);
  263. if ($checkOrderCount >= $buyLimit) {
  264. RedisService::clear($cacheLockKey);
  265. $this->error = $buyLimit>1?"抱歉该创业礼包仅限购买{$buyLimit}次":'抱歉,您已经购买过该礼包';
  266. return false;
  267. }
  268. }
  269. }
  270. // 收货地址信息
  271. $addressInfo = MemberAddressService::make()->getBindInfo($userId, $addressId);
  272. $realname = isset($addressInfo['realname']) ? $addressInfo['realname'] : '';
  273. $mobile = isset($addressInfo['mobile']) ? $addressInfo['mobile'] : '';
  274. $area = isset($addressInfo['area']) ? $addressInfo['area'] : '';
  275. $address = isset($addressInfo['address']) ? $addressInfo['address'] : '';
  276. if (empty($addressInfo) || empty($realname) || empty($mobile) || empty($area) || empty($address)) {
  277. RedisService::clear($cacheLockKey);
  278. $this->error = '收货地址信息错误,请核对后重试~';
  279. return false;
  280. }
  281. // 是否开启分账功能
  282. $payTotal = moneyFormat($orderTotal + $deliveryFee, 2); // 含运费支付金额
  283. if (env('PAY_DEBUG')) {
  284. $payTotal = 0.01;
  285. }
  286. // 订单数据
  287. $order = [
  288. 'order_no' => $orderNo,
  289. 'user_id' => $userId,
  290. 'store_id' => $storeId,
  291. 'meal_id' => $mealId,
  292. 'type' => $type,
  293. 'total' => $goodsTotal, // 商品总价
  294. 'num' => $orderCount,
  295. 'bd_score' => $bdScoreTotal, // 折扣后商品总价(不含运费)
  296. 'profit_total' => $profitTotal, // 折扣后商品总价(不含运费)
  297. 'pay_money' => $orderTotal, // 折扣后商品总价(不含运费)
  298. 'pay_total' => $type==2?moneyFormat($orderTotal + $bdScoreTotal,2):$orderTotal, // 折扣后商品总价(不含运费)
  299. 'pay_status' => $type==2? 30 : 10, // 折扣后商品总价(不含运费)
  300. 'discount_point' => $discountPoint,
  301. 'discount_total' => $discountTotal, // 折扣金额
  302. 'delivery_fee' => $deliveryFee, // 运费
  303. 'receiver_name' => $realname,
  304. 'receiver_mobile' => $mobile,
  305. 'receiver_area' => $area,
  306. 'receiver_address' => $address,
  307. 'create_time' => time(),
  308. 'update_time' => time(),
  309. 'status' => 1,
  310. 'mark' => 1,
  311. ];
  312. // 订单处理
  313. DB::beginTransaction();
  314. if (!$orderId = $this->model->insertGetId($order)) {
  315. DB::rollBack();
  316. $this->error = '创建订单失败';
  317. RedisService::clear($cacheLockKey);
  318. return false;
  319. }
  320. // 订单商品
  321. if ($orderGoods && !OrderGoodsModel::insert($orderGoods)) {
  322. DB::rollBack();
  323. $this->error = '处理订单商品错误';
  324. RedisService::clear($cacheLockKey);
  325. return false;
  326. }
  327. // 创业礼包分单
  328. if ($type == 2) {
  329. $data = $order;
  330. $data['total'] = moneyFormat($data['total'] / 6);
  331. $data['bd_score'] = moneyFormat($bdScoreTotal / 6, 2);
  332. $data['profit_total'] = moneyFormat($profitTotal / 6, 2);
  333. $data['pay_total'] = moneyFormat($orderTotal / 6, 2);
  334. $data['pay_money'] = moneyFormat($order['pay_money'] / 6, 2);
  335. $subOrders = [];
  336. for ($i = 1; $i <= 6; $i++) {
  337. $data['order_no'] = get_order_num('BS');
  338. $data['main_no'] = $orderNo;
  339. if ($i == 6) {
  340. $data['total'] = round($order['total'] / 6, 2);
  341. $data['bd_score'] = round($bdScoreTotal / 6, 2);
  342. $data['profit_total'] = round($profitTotal / 6, 2);
  343. $data['pay_total'] = round($orderTotal / 6, 2);
  344. $data['pay_money'] = round($order['pay_money'] / 6, 2);
  345. }
  346. $subOrders[] = $data;
  347. }
  348. //
  349. if ($subOrders && !$this->model->insert($subOrders)) {
  350. DB::rollBack();
  351. $this->error = '处理商品订单失败';
  352. RedisService::clear($cacheLockKey);
  353. return false;
  354. }
  355. // 扣除报单积分
  356. if($bdScoreTotal>0){
  357. if(!MemberModel::where(['id'=>$userId])->update(['bd_score'=>DB::raw("bd_score - {$bdScoreTotal}"),'update_time'=>time()])){
  358. DB::rollBack();
  359. $this->error = '报单积分扣除失败';
  360. RedisService::clear($cacheLockKey);
  361. return false;
  362. }
  363. $data = [
  364. 'user_id'=>$userId,
  365. 'source_order_no'=>$orderNo,
  366. 'user_type'=> 1,
  367. 'account_type'=> 3, // 报单积分
  368. 'type'=> 1,
  369. 'money'=> -$bdScoreTotal,
  370. 'after_money'=>moneyFormat($bdScore - $bdScoreTotal,2),
  371. 'date'=>date('Y-m-d'),
  372. 'create_time'=>time(),
  373. 'remark'=> '创业礼包支付',
  374. 'status'=>1,
  375. 'mark'=>1
  376. ];
  377. if(!AccountLogModel::insertGetId($data)){
  378. Db::rollBack();
  379. $this->error = '付款处理失败';
  380. return false;
  381. }
  382. }
  383. }
  384. // 佣金数据
  385. if(!$commission = SettleService::make()->commissionCount($order,$orderGoods,$userInfo, $type)){
  386. Db::rollBack();
  387. $this->error = '订单处理失败';
  388. return false;
  389. }
  390. // 获取支付参数
  391. /* TODO 支付处理 */
  392. $payOrder = [
  393. 'type' => 1,
  394. 'order_no' => $orderNo,
  395. 'is_revenue' => isset($order['is_revenue'])?$order['is_revenue']:2,
  396. 'pay_money' => $payTotal,
  397. 'body' => '订单付款',
  398. 'openid' => $openid
  399. ];
  400. // 调起支付
  401. $payment = PaymentService::make()->minPay($userInfo, $payOrder, 'store');
  402. if (empty($payment)) {
  403. //DB::rollBack();
  404. RedisService::clear($cacheLockKey);
  405. $this->error = PaymentService::make()->getError();
  406. return false;
  407. }
  408. // 商品库存扣除
  409. if ($orderGoods) {
  410. foreach ($orderGoods as $goods) {
  411. $id = isset($goods['goods_id']) ? $goods['goods_id'] : 0;
  412. $num = isset($goods['num']) ? $goods['num'] : 0;
  413. $skuId = isset($goods['sku_id']) ? $goods['sku_id'] : 0;
  414. if ($id && !GoodsModel::where(['id' => $id])->update(['stock' => DB::raw("stock - {$num}"), 'update_time' => time()])) {
  415. DB::rollBack();
  416. RedisService::clear($cacheLockKey);
  417. $this->error = '商品库存处理失败';
  418. return false;
  419. }
  420. if ($skuId && !GoodsSkuModel::where(['id' => $skuId])->update(['stock' => DB::raw("stock - {$num}"), 'update_time' => time()])) {
  421. DB::rollBack();
  422. RedisService::clear($cacheLockKey);
  423. $this->error = '商品库存处理失败';
  424. return false;
  425. }
  426. }
  427. }
  428. // 用户操作记录
  429. DB::commit();
  430. $this->error = '订单创建成功,请前往支付~';
  431. RedisService::clear($cacheLockKey);
  432. return [
  433. 'order_id' => $orderId,
  434. 'payment' => $payment,
  435. 'total' => $payOrder['pay_money'],
  436. 'pay_type' => 10,
  437. ];
  438. }
  439. /**
  440. * 创业大礼包验证
  441. * @param $userId
  442. * @param $goodsId
  443. * @return array|mixed
  444. */
  445. public function checkBusinessOrder($userId, $goodsId)
  446. {
  447. $cacheKey = "caches:orders:check_order:{$userId}_{$goodsId}";
  448. $data = RedisService::get($cacheKey);
  449. if ($data) {
  450. return $data;
  451. }
  452. $data = $this->model->where(['user_id' => $userId, 'meal_id' => $goodsId, 'mark' => 1])
  453. ->where('status', '<=', 5)
  454. ->where('refund_status', '<=', 0)
  455. ->count('id');
  456. $data = $data ? $data->toArray() : [];
  457. if ($data) {
  458. RedisService::set($cacheKey, $data, rand(5, 10));
  459. }
  460. return $data;
  461. }
  462. /**
  463. * 订单支付
  464. * @param $userId
  465. * @param $id
  466. * @return array|false
  467. */
  468. public function pay($userId, $id)
  469. {
  470. if ($id <= 0) {
  471. $this->error = '请选择支付订单';
  472. return false;
  473. }
  474. // 缓存锁
  475. $cacheLockKey = "caches:orders:pay_lock:{$userId}_{$id}";
  476. if (RedisService::get($cacheLockKey)) {
  477. $this->error = '订单处理中~';
  478. return false;
  479. }
  480. // 商品数据
  481. RedisService::set($cacheLockKey, ['order_id' => $id, 'user_id' => $userId], rand(3, 5));
  482. // 用户信息
  483. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  484. ->select(['id', 'openid', 'mobile', 'nickname', 'realname', 'balance', 'status'])
  485. ->first();
  486. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  487. $openid = isset($userInfo['openid']) ? $userInfo['openid'] : '';
  488. if (empty($userInfo) || $status != 1) {
  489. $this->error = 1045;
  490. RedisService::clear($cacheLockKey);
  491. return false;
  492. }
  493. if (empty($openid)) {
  494. $this->error = '用户微信未授权,请重新授权登录';
  495. RedisService::clear($cacheLockKey);
  496. return false;
  497. }
  498. // 订单信息
  499. $info = $this->model->where(['id' => $id, 'mark' => 1])
  500. ->select(['id', 'order_no', 'pay_total', 'delivery_fee', 'status'])
  501. ->first();
  502. $orderTotal = isset($info['pay_total']) ? $info['pay_total'] : 0;
  503. $deliveryFee = isset($info['delivery_fee']) ? $info['delivery_fee'] : 0;
  504. $orderNo = isset($info['order_no']) ? $info['order_no'] : '';
  505. $status = isset($info['status']) ? $info['status'] : 0;
  506. if (empty($info) || empty($orderNo)) {
  507. $this->error = '订单信息不存在';
  508. RedisService::clear($cacheLockKey);
  509. return false;
  510. }
  511. if ($status != 1) {
  512. $this->error = '订单已支付';
  513. RedisService::clear($cacheLockKey);
  514. return false;
  515. }
  516. // 获取支付参数
  517. /* TODO 支付处理 */
  518. $payOrder = [
  519. 'type' => 1,
  520. 'order_no' => $orderNo,
  521. 'pay_money' => moneyFormat($orderTotal + $deliveryFee),
  522. 'body' => '购物消费',
  523. 'openid' => $openid
  524. ];
  525. // 调起支付
  526. $payment = PaymentService::make()->minPay($userInfo, $payOrder, 'store');
  527. if (empty($payment)) {
  528. DB::rollBack();
  529. RedisService::clear($cacheLockKey);
  530. $this->error = PaymentService::make()->getError();
  531. return false;
  532. }
  533. // 用户操作记录
  534. DB::commit();
  535. $this->error = '支付请求成功,请前往支付~';
  536. RedisService::clear($cacheLockKey);
  537. return [
  538. 'order_id' => $id,
  539. 'payment' => $payment,
  540. 'total' => $payOrder['pay_money'],
  541. 'pay_type' => 10,
  542. ];
  543. }
  544. /**
  545. * 订单取消
  546. * @param $userId
  547. * @param $orderId
  548. * @return array|false
  549. */
  550. public function cancel($userId, $orderId)
  551. {
  552. if ($orderId <= 0) {
  553. $this->error = '请选择订单';
  554. return false;
  555. }
  556. // 缓存锁
  557. $cacheLockKey = "caches:orders:cancel_lock:{$userId}_{$orderId}";
  558. if (RedisService::get($cacheLockKey)) {
  559. $this->error = '订单处理中~';
  560. return false;
  561. }
  562. RedisService::set($cacheLockKey, ['order_id' => $orderId, 'user_id' => $userId], rand(3, 5));
  563. // 用户信息
  564. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  565. ->select(['id', 'openid', 'mobile', 'nickname', 'realname', 'balance', 'status'])
  566. ->first();
  567. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  568. if (empty($userInfo) || $status != 1) {
  569. $this->error = 1045;
  570. RedisService::clear($cacheLockKey);
  571. return false;
  572. }
  573. // 订单信息
  574. $info = $this->model->where(['id' => $orderId, 'mark' => 1])
  575. ->select(['id', 'order_no', 'pay_total', 'status'])
  576. ->first();
  577. $orderNo = isset($info['order_no']) ? $info['order_no'] : '';
  578. $status = isset($info['status']) ? $info['status'] : 0;
  579. if (empty($info) || empty($orderNo)) {
  580. $this->error = '订单信息不存在';
  581. RedisService::clear($cacheLockKey);
  582. return false;
  583. }
  584. if ($status != 1) {
  585. $this->error = '订单已支付';
  586. RedisService::clear($cacheLockKey);
  587. return false;
  588. }
  589. $orderGoods = OrderGoodsModel::where(['order_no' => $orderNo, 'mark' => 1])
  590. ->select(['goods_id', 'num', 'sku_id'])
  591. ->get();
  592. DB::beginTransaction();
  593. if ($orderGoods) {
  594. foreach ($orderGoods as $goods) {
  595. $goodsId = isset($goods['goods_id']) ? $goods['goods_id'] : 0;
  596. $num = isset($goods['num']) ? $goods['num'] : 0;
  597. $skuId = isset($goods['sku_id']) ? $goods['sku_id'] : 0;
  598. if ($goodsId) {
  599. GoodsModel::where(['id' => $goodsId])->update(['stock' => DB::raw("stock + {$num}"), 'update_time' => time()]);
  600. }
  601. if ($skuId) {
  602. GoodsSkuModel::where(['id' => $skuId])->update(['stock' => DB::raw("stock + {$num}"), 'update_time' => time()]);
  603. }
  604. }
  605. }
  606. $this->error = '取消订单成功';
  607. $this->model->where(['user_id' => $userId, 'mark' => 0])->where('update_time', '<=', time() - 300)->delete();
  608. OrderGoodsModel::where(['order_no' => $orderNo, 'mark' => 0])->where('update_time', '<=', time() - 300)->delete();
  609. $this->model->where(['id' => $orderId])->update(['mark' => 0, 'update_time' => time()]);
  610. OrderGoodsModel::where(['order_no' => $orderNo])->update(['mark' => 0, 'update_time' => time()]);
  611. DB::commit();
  612. return ['id' => $orderId];
  613. }
  614. /**
  615. * 订单删除隐藏
  616. * @param $userId
  617. * @param $orderId
  618. * @return array|false
  619. */
  620. public function hide($userId, $orderId)
  621. {
  622. if ($orderId <= 0) {
  623. $this->error = '请选择订单';
  624. return false;
  625. }
  626. // 缓存锁
  627. $cacheLockKey = "caches:orders:hide_lock:{$userId}_{$orderId}";
  628. if (RedisService::get($cacheLockKey)) {
  629. $this->error = '订单删除中~';
  630. return false;
  631. }
  632. RedisService::set($cacheLockKey, ['order_id' => $orderId, 'user_id' => $userId], rand(3, 5));
  633. // 用户信息
  634. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  635. ->select(['id', 'openid', 'mobile', 'nickname', 'realname', 'balance', 'status'])
  636. ->first();
  637. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  638. if (empty($userInfo) || $status != 1) {
  639. $this->error = 1045;
  640. RedisService::clear($cacheLockKey);
  641. return false;
  642. }
  643. // 订单信息
  644. $info = $this->model->where(['id' => $orderId, 'mark' => 1])
  645. ->select(['id', 'order_no', 'pay_total', 'status'])
  646. ->first();
  647. $orderNo = isset($info['order_no']) ? $info['order_no'] : '';
  648. $status = isset($info['status']) ? $info['status'] : 0;
  649. if (empty($info) || empty($orderNo)) {
  650. $this->error = '订单信息不存在';
  651. RedisService::clear($cacheLockKey);
  652. return false;
  653. }
  654. if ($status != 4) {
  655. $this->error = '订单未完成';
  656. RedisService::clear($cacheLockKey);
  657. return false;
  658. }
  659. $this->error = '删除订单成功';
  660. $this->model->where(['id' => $orderId])->update(['is_hide' => 1, 'update_time' => time()]);
  661. return ['id' => $orderId];
  662. }
  663. /**
  664. * 订单完成
  665. * @param $userId 订单用户ID
  666. * @param $id 订单ID
  667. * @return array|false
  668. */
  669. public function complete($userId, $id, $check = true)
  670. {
  671. if ($id <= 0) {
  672. $this->error = '请选择订单';
  673. return false;
  674. }
  675. // 缓存锁
  676. $cacheLockKey = "caches:orders:complete_lock:{$userId}_{$id}";
  677. if (RedisService::get($cacheLockKey)) {
  678. $this->error = '订单处理中~';
  679. return false;
  680. }
  681. // 商品数据
  682. RedisService::set($cacheLockKey, ['order_id' => $id, 'user_id' => $userId], rand(3, 5));
  683. // 用户信息
  684. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  685. ->select(['id', 'openid', 'mobile', 'parent_id', 'nickname', 'realname', 'balance', 'status'])
  686. ->first();
  687. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  688. $parentId = isset($userInfo['parent_id']) ? $userInfo['parent_id'] : 0;
  689. if ($check && (empty($userInfo) || $status != 1)) {
  690. $this->error = 1045;
  691. RedisService::clear($cacheLockKey);
  692. return false;
  693. }
  694. // 订单信息
  695. $info = $this->model->with(['orderGoods','commission'])->where(['id' => $id, 'mark' => 1])
  696. ->select(['id', 'order_no','type', 'user_id', 'store_id', 'total', 'pay_total', 'delivery_no', 'delivery_company', 'delivery_code', 'status'])
  697. ->first();
  698. $orderNo = isset($info['order_no']) ? $info['order_no'] : '';
  699. $deliveryNo = isset($info['delivery_no']) ? $info['delivery_no'] : '';
  700. $deliverCompany = isset($info['delivery_company']) ? $info['delivery_company'] : '';
  701. $orderUserId = isset($info['user_id']) ? $info['user_id'] : 0;
  702. $storeId = isset($info['store_id']) ? $info['store_id'] : 0;
  703. $orderType = isset($info['type']) ? $info['type'] : 0;
  704. $orderTotal = isset($info['total']) ? $info['total'] : 0;
  705. $status = isset($info['status']) ? $info['status'] : 0;
  706. $commission = isset($info['commission']) ? $info['commission'] : [];
  707. $bonus = isset($commission['bonus'])?$commission['bonus'] : 0;
  708. $orderGoods = isset($info['order_goods']) ? $info['order_goods'] : [];
  709. if (empty($info) || empty($orderNo)) {
  710. $this->error = '订单信息不存在';
  711. RedisService::clear($cacheLockKey);
  712. return false;
  713. }
  714. if ($status != 3) {
  715. $this->error = '订单未发货';
  716. RedisService::clear($cacheLockKey);
  717. return false;
  718. }
  719. if (empty($deliveryNo) || empty($deliverCompany)) {
  720. $this->error = '订单发货信息错误,请联系客服';
  721. $this->model->where(['id' => $id])->update(['is_complete' => 1, 'complete_remark' => $this->error]);
  722. RedisService::clear("caches:orders:completeList");
  723. RedisService::clear($cacheLockKey);
  724. return false;
  725. }
  726. DB::beginTransaction();
  727. $completeStatus = env('ORDER_COMPLETE_STATUS', 5);
  728. $updateData = ['status' => $completeStatus, 'complete_at' => date('Y-m-d H:i:s'), 'update_time' => time()];
  729. if (!$check) {
  730. $updateData['is_complete'] = 1;
  731. $updateData['complete_remark'] = '自动收货';
  732. }
  733. $this->model->where(['id' => $id])->update($updateData);
  734. // 商家订单数据统计
  735. $updateData = ['order_count' => DB::raw('order_count+1'), 'order_total' => DB::raw("order_total + {$orderTotal}")];
  736. StoreModel::where(['id' => $storeId])->update($updateData);
  737. // 商品销量数据
  738. if ($orderGoods) {
  739. $counts = [];
  740. foreach ($orderGoods as $item) {
  741. $counts[$item['goods_id']] = isset($counts[$item['goods_id']]) ? $counts[$item['goods_id']] : 0;
  742. $counts[$item['goods_id']] += $item['num'];
  743. }
  744. if ($counts) {
  745. foreach ($counts as $id => $v) {
  746. GoodsModel::where(['id' => $id])->update(['sales' => DB::raw("sales + {$v}"), 'update_time' => time()]);
  747. }
  748. }
  749. }
  750. // 结算商家收益
  751. if ($bonus && SettleService::make()->storeBonus($storeId, $bonus, $info) < 0) {
  752. DB::rollBack();
  753. $this->error = SettleService::make()->getError();
  754. RedisService::clear($cacheLockKey);
  755. return false;
  756. }
  757. if($orderType==2){
  758. // 创业礼包结算
  759. if (SettleService::make()->businessBonus($orderUserId, $orderTotal, $commission, $info) < 0) {
  760. DB::rollBack();
  761. $this->error = SettleService::make()->getError();
  762. RedisService::clear($cacheLockKey);
  763. return false;
  764. }
  765. }else{
  766. // 商城奖励结算
  767. if (SettleService::make()->shopBonus($orderUserId, $orderTotal,$commission, $info) < 0) {
  768. DB::rollBack();
  769. $this->error = SettleService::make()->getError();
  770. RedisService::clear($cacheLockKey);
  771. return false;
  772. }
  773. }
  774. DB::commit();
  775. $this->error = '确认收货成功';
  776. RedisService::clear("caches:orders:completeList");
  777. RedisService::clear("caches:orders:revenueList");
  778. return ['id' => $id, 'msg' => $this->error];
  779. }
  780. /**
  781. * 售后或退款
  782. * @param $userId
  783. * @param $params
  784. * @return array|false
  785. */
  786. public function after($userId, $params)
  787. {
  788. $id = isset($params['id']) ? $params['id'] : 0;
  789. $afterType = isset($params['after_type']) ? $params['after_type'] : 1;
  790. if ($id <= 0) {
  791. $this->error = '请选择订单';
  792. return false;
  793. }
  794. // 缓存锁
  795. $cacheLockKey = "caches:orders:after_lock:{$userId}_{$id}";
  796. if (RedisService::get($cacheLockKey)) {
  797. $this->error = '订单处理中~';
  798. return false;
  799. }
  800. // 商品数据
  801. RedisService::set($cacheLockKey, ['params' => $params, 'user_id' => $userId], rand(3, 5));
  802. // 用户信息
  803. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  804. ->select(['id', 'openid', 'mobile', 'nickname', 'realname', 'balance', 'status'])
  805. ->first();
  806. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  807. if (empty($userInfo) || $status != 1) {
  808. $this->error = 1045;
  809. RedisService::clear($cacheLockKey);
  810. return false;
  811. }
  812. // 订单信息
  813. $info = $this->model->where(['id' => $id, 'mark' => 1])
  814. ->select(['id', 'order_no', 'after_type', 'refund_status', 'pay_total', 'status'])
  815. ->first();
  816. $orderNo = isset($info['order_no']) ? $info['order_no'] : '';
  817. $status = isset($info['status']) ? $info['status'] : 0;
  818. $refundStatus = isset($info['refund_status']) ? $info['refund_status'] : 0;
  819. if (empty($info) || empty($orderNo)) {
  820. $this->error = '订单信息不存在';
  821. RedisService::clear($cacheLockKey);
  822. return false;
  823. }
  824. if ($status == 1) {
  825. $this->error = '订单未支付';
  826. RedisService::clear($cacheLockKey);
  827. return false;
  828. }
  829. if ($status == 4 && $afterType == 2) {
  830. $this->error = '订单已完成';
  831. RedisService::clear($cacheLockKey);
  832. return false;
  833. }
  834. if ($refundStatus > 0 && $refundStatus != 4) {
  835. $this->error = '订单售后处理中';
  836. RedisService::clear($cacheLockKey);
  837. return false;
  838. }
  839. $afterRealname = isset($params['after_realname']) ? $params['after_realname'] : '';
  840. $afterPhone = isset($params['after_phone']) ? $params['after_phone'] : '';
  841. $afterRemark = isset($params['after_remark']) ? $params['after_remark'] : '';
  842. if ($afterType == 1) {
  843. if (empty($afterRealname) || empty($afterPhone) || empty($afterRemark)) {
  844. $this->error = '请填写售后信息';
  845. RedisService::clear($cacheLockKey);
  846. return false;
  847. }
  848. }
  849. $data = [
  850. 'after_type' => $afterType,
  851. 'after_realname' => $afterRealname,
  852. 'after_phone' => $afterPhone,
  853. 'after_remark' => $afterRemark,
  854. 'refund_remark' => isset($params['refund_remark']) ? $params['refund_remark'] : '',
  855. 'refund_status' => 3,
  856. 'update_time' => time()
  857. ];
  858. $this->model->where(['id' => $id])->update($data);
  859. $this->error = '订单申请售后成功';
  860. return ['id' => $id];
  861. }
  862. /**
  863. * 物流查询
  864. * @param $id
  865. * @return array|false|mixed
  866. */
  867. public function getDelivery($id)
  868. {
  869. $info = $this->model->where(['id' => $id, 'mark' => 1])->first();
  870. $deliveryNo = isset($info['delivery_no']) ? $info['delivery_no'] : '';
  871. $deliveryCode = isset($info['delivery_code']) ? $info['delivery_code'] : '';
  872. $mobile = isset($info['receiver_mobile']) ? $info['receiver_mobile'] : '';
  873. $receiverArea = isset($info['receiver_area']) && $info['receiver_area'] ? $info['receiver_area'] : '';
  874. if (empty($info)) {
  875. $this->error = '请选择订单';
  876. return false;
  877. }
  878. $cacheKey = "caches:kd100:order_{$id}";
  879. $data = RedisService::get($cacheKey);
  880. if ($data) {
  881. return $data;
  882. }
  883. $result = Kd100Service::make()->query($deliveryNo, $mobile, $deliveryCode, $receiverArea);
  884. RedisService::set($cacheKey . '_result', $result, 300);
  885. $status = isset($result['status']) ? $result['status'] : 0;
  886. $data = isset($result['data']) ? $result['data'] : [];
  887. $courierInfo = isset($result['courierInfo']) ? $result['courierInfo'] : [];
  888. $arrivalTime = isset($result['arrivalTime']) ? $result['arrivalTime'] : '';
  889. $predictedRoute = isset($result['predictedRoute']) ? $result['predictedRoute'] : [];
  890. $predictedData = $predictedRoute ? end($predictedRoute) : [];
  891. $arrivalData = [];
  892. if ($arrivalTime) {
  893. $arrivalData['arrivalTime'] = dayFormat(strtotime($arrivalTime . ':00:00'));
  894. $arrivalData['predictedData'] = $predictedData;
  895. }
  896. if ($courierInfo && $courierInfo['deliveryManPhone']) {
  897. $courierInfo['deliveryManPhone'] = explode(',', $courierInfo['deliveryManPhone']);
  898. $courierInfo['deliveryPhone'] = $courierInfo['deliveryManPhone'][1] ? $courierInfo['deliveryManPhone'][1] : $courierInfo['deliveryManPhone'][0];
  899. }
  900. if ($data && $status == 200) {
  901. RedisService::set($cacheKey, ['info' => $courierInfo, 'arrivalData' => $arrivalData, 'list' => $data], 1200);
  902. }
  903. return $data ? ['info' => $courierInfo, 'arrivalData' => $arrivalData, 'list' => $data] : [];
  904. }
  905. /**
  906. * 已发货待完成订单
  907. * @return array|mixed
  908. */
  909. public function getCompleteOrders()
  910. {
  911. $cacheKey = "caches:orders:completeList";
  912. $datas = RedisService::get($cacheKey);
  913. if ($datas) {
  914. return $datas;
  915. }
  916. $completeDay = ConfigService::make()->getConfigByCode('order_complete_day', 7);
  917. $limitNum = ConfigService::make()->getConfigByCode('order_complete_batch_num', 300);
  918. $limitNum = $limitNum > 10 && $limitNum < 2000 ? $limitNum : 300;
  919. $completeDay = $completeDay >= 1 && $completeDay < 30 ? $completeDay : 7;
  920. $datas = $this->model->where(['status' => 3, 'is_complete' => 2, 'mark' => 1])
  921. ->whereNotNull('delivery_no')
  922. ->select(['id', 'user_id', 'order_no', 'status'])
  923. ->where('pay_at', '<=', date('Y-m-d H:i:s', time() - $completeDay * 86400))
  924. ->limit($limitNum)
  925. ->get();
  926. $datas = $datas ? $datas->toArray() : [];
  927. if ($datas) {
  928. RedisService::set($cacheKey, $datas, rand(300, 600));
  929. }
  930. return $datas;
  931. }
  932. /**
  933. * 已完成,待分账订单
  934. * @return array|mixed
  935. */
  936. public function getRevenueOrderList()
  937. {
  938. $cacheKey = "caches:orders:revenueList";
  939. $datas = RedisService::get($cacheKey);
  940. if ($datas) {
  941. return $datas;
  942. }
  943. $limitNum = ConfigService::make()->getConfigByCode('order_revenue_batch_num', 300);
  944. $limitNum = $limitNum > 10 && $limitNum < 2000 ? $limitNum : 300;
  945. $datas = $this->model->where(['status' => 4, 'is_revenue' => 1, 'revenue_status' => 2, 'mark' => 1])
  946. ->select(['id', 'user_id', 'pay_total', 'order_no', 'revenue_no', 'transaction_id', 'status'])
  947. ->limit($limitNum)
  948. ->get();
  949. $datas = $datas ? $datas->toArray() : [];
  950. if ($datas) {
  951. RedisService::set($cacheKey, $datas, rand(300, 600));
  952. }
  953. return $datas;
  954. }
  955. /**
  956. * 订单分账处理
  957. * @param $id
  958. * @return false
  959. * @throws \Yansongda\Pay\Exception\ContainerException
  960. * @throws \Yansongda\Pay\Exception\InvalidParamsException
  961. */
  962. public function revenue($id)
  963. {
  964. if ($id <= 0) {
  965. $this->error = '订单参数错误';
  966. return false;
  967. }
  968. // 缓存锁
  969. $cacheLockKey = "caches:orders:revenue_lock:{$id}";
  970. if (RedisService::get($cacheLockKey)) {
  971. $this->error = '订单分账处理中~';
  972. return false;
  973. }
  974. // 是否设置分账账户
  975. $revenueOpenid = ConfigService::make()->getConfigByCode('order_revenue_openid', '');
  976. if (empty($revenueOpenid)) {
  977. $this->error = '订单分账账户未配置';
  978. return false;
  979. }
  980. // 订单信息
  981. RedisService::set($cacheLockKey, ['id' => $id, 'date' => date('Y-m-d H:i:s')], 20);
  982. $info = $this->model->where(['id' => $id, 'mark' => 1])
  983. ->select(['id', 'order_no', 'revenue_no', 'user_id', 'transaction_id', 'pay_total', 'is_revenue', 'revenue_status', 'revenue_amount', 'status'])
  984. ->first();
  985. $revenueOrderNo = isset($info['revenue_no']) ? $info['revenue_no'] : '';
  986. $revenueAmount = isset($info['revenue_amount']) ? $info['revenue_amount'] : 0;
  987. $status = isset($info['status']) ? $info['status'] : 0;
  988. $isRevenue = isset($info['is_revenue']) ? $info['is_revenue'] : 0;
  989. $revenueStatus = isset($info['revenue_status']) ? $info['revenue_status'] : 0;
  990. if ($status != 4) {
  991. RedisService::clear($cacheLockKey);
  992. $this->error = '订单状态错误,未完成收货的订单无法分账';
  993. return false;
  994. }
  995. if ($isRevenue != 1) {
  996. RedisService::clear($cacheLockKey);
  997. $this->error = '该订单不是分账订单';
  998. return false;
  999. }
  1000. if ($revenueStatus != 2) {
  1001. RedisService::clear($cacheLockKey);
  1002. $this->error = '该订单分账已处理完成';
  1003. return false;
  1004. }
  1005. if ($revenueAmount <= 0) {
  1006. RedisService::clear($cacheLockKey);
  1007. $this->error = '订单分账金额不足';
  1008. return false;
  1009. }
  1010. $order = [
  1011. 'transaction_id' => $info['transaction_id'],
  1012. 'out_order_no' => $revenueOrderNo,
  1013. 'body' => '订单分账',
  1014. 'amount' => $revenueAmount,
  1015. 'unsplit' => true, // 只分一次
  1016. ];
  1017. $result = PaymentService::make()->profitsharing($revenueOpenid, $order);
  1018. $state = isset($result->state) ? $result->state : 0;
  1019. $message = isset($result->message) ? $result->message : '分账失败';
  1020. $orderId = isset($result->order_id) ? $result->order_id : '';
  1021. if ($state == 'FINISHED') {
  1022. $this->model->where(['id' => $id])->update(['revenue_status' => 1, 'revenue_order_id' => $orderId, 'update_time' => time()]);
  1023. RedisService::clear($cacheLockKey);
  1024. RedisService::clear("caches:orders:revenueList");
  1025. $this->error = '分账处理成功';
  1026. return true;
  1027. } else {
  1028. RedisService::clear($cacheLockKey);
  1029. $this->error = $message;
  1030. return false;
  1031. }
  1032. }
  1033. }