OrderService.php 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  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 + $bdScore,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. ->orderBy('id', 'desc')
  456. ->count('id');
  457. $data = $data ? $data->toArray() : [];
  458. if ($data) {
  459. RedisService::set($cacheKey, $data, rand(5, 10));
  460. }
  461. return $data;
  462. }
  463. /**
  464. * 订单支付
  465. * @param $userId
  466. * @param $id
  467. * @return array|false
  468. */
  469. public function pay($userId, $id)
  470. {
  471. if ($id <= 0) {
  472. $this->error = '请选择支付订单';
  473. return false;
  474. }
  475. // 缓存锁
  476. $cacheLockKey = "caches:orders:pay_lock:{$userId}_{$id}";
  477. if (RedisService::get($cacheLockKey)) {
  478. $this->error = '订单处理中~';
  479. return false;
  480. }
  481. // 商品数据
  482. RedisService::set($cacheLockKey, ['order_id' => $id, 'user_id' => $userId], rand(3, 5));
  483. // 用户信息
  484. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  485. ->select(['id', 'openid', 'mobile', 'nickname', 'realname', 'balance', 'status'])
  486. ->first();
  487. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  488. $openid = isset($userInfo['openid']) ? $userInfo['openid'] : '';
  489. if (empty($userInfo) || $status != 1) {
  490. $this->error = 1045;
  491. RedisService::clear($cacheLockKey);
  492. return false;
  493. }
  494. if (empty($openid)) {
  495. $this->error = '用户微信未授权,请重新授权登录';
  496. RedisService::clear($cacheLockKey);
  497. return false;
  498. }
  499. // 订单信息
  500. $info = $this->model->where(['id' => $id, 'mark' => 1])
  501. ->select(['id', 'order_no', 'pay_total', 'delivery_fee', 'status'])
  502. ->first();
  503. $orderTotal = isset($info['pay_total']) ? $info['pay_total'] : 0;
  504. $deliveryFee = isset($info['delivery_fee']) ? $info['delivery_fee'] : 0;
  505. $orderNo = isset($info['order_no']) ? $info['order_no'] : '';
  506. $status = isset($info['status']) ? $info['status'] : 0;
  507. if (empty($info) || empty($orderNo)) {
  508. $this->error = '订单信息不存在';
  509. RedisService::clear($cacheLockKey);
  510. return false;
  511. }
  512. if ($status != 1) {
  513. $this->error = '订单已支付';
  514. RedisService::clear($cacheLockKey);
  515. return false;
  516. }
  517. // 获取支付参数
  518. /* TODO 支付处理 */
  519. $payOrder = [
  520. 'type' => 1,
  521. 'order_no' => $orderNo,
  522. 'pay_money' => moneyFormat($orderTotal + $deliveryFee),
  523. 'body' => '购物消费',
  524. 'openid' => $openid
  525. ];
  526. // 调起支付
  527. $payment = PaymentService::make()->minPay($userInfo, $payOrder, 'store');
  528. if (empty($payment)) {
  529. DB::rollBack();
  530. RedisService::clear($cacheLockKey);
  531. $this->error = PaymentService::make()->getError();
  532. return false;
  533. }
  534. // 用户操作记录
  535. DB::commit();
  536. $this->error = '支付请求成功,请前往支付~';
  537. RedisService::clear($cacheLockKey);
  538. return [
  539. 'order_id' => $id,
  540. 'payment' => $payment,
  541. 'total' => $payOrder['pay_money'],
  542. 'pay_type' => 10,
  543. ];
  544. }
  545. /**
  546. * 订单取消
  547. * @param $userId
  548. * @param $orderId
  549. * @return array|false
  550. */
  551. public function cancel($userId, $orderId)
  552. {
  553. if ($orderId <= 0) {
  554. $this->error = '请选择订单';
  555. return false;
  556. }
  557. // 缓存锁
  558. $cacheLockKey = "caches:orders:cancel_lock:{$userId}_{$orderId}";
  559. if (RedisService::get($cacheLockKey)) {
  560. $this->error = '订单处理中~';
  561. return false;
  562. }
  563. RedisService::set($cacheLockKey, ['order_id' => $orderId, 'user_id' => $userId], rand(3, 5));
  564. // 用户信息
  565. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  566. ->select(['id', 'openid', 'mobile', 'nickname', 'realname', 'balance', 'status'])
  567. ->first();
  568. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  569. if (empty($userInfo) || $status != 1) {
  570. $this->error = 1045;
  571. RedisService::clear($cacheLockKey);
  572. return false;
  573. }
  574. // 订单信息
  575. $info = $this->model->where(['id' => $orderId, 'mark' => 1])
  576. ->select(['id', 'order_no', 'pay_total', 'status'])
  577. ->first();
  578. $orderNo = isset($info['order_no']) ? $info['order_no'] : '';
  579. $status = isset($info['status']) ? $info['status'] : 0;
  580. if (empty($info) || empty($orderNo)) {
  581. $this->error = '订单信息不存在';
  582. RedisService::clear($cacheLockKey);
  583. return false;
  584. }
  585. if ($status != 1) {
  586. $this->error = '订单已支付';
  587. RedisService::clear($cacheLockKey);
  588. return false;
  589. }
  590. $orderGoods = OrderGoodsModel::where(['order_no' => $orderNo, 'mark' => 1])
  591. ->select(['goods_id', 'num', 'sku_id'])
  592. ->get();
  593. DB::beginTransaction();
  594. if ($orderGoods) {
  595. foreach ($orderGoods as $goods) {
  596. $goodsId = isset($goods['goods_id']) ? $goods['goods_id'] : 0;
  597. $num = isset($goods['num']) ? $goods['num'] : 0;
  598. $skuId = isset($goods['sku_id']) ? $goods['sku_id'] : 0;
  599. if ($goodsId) {
  600. GoodsModel::where(['id' => $goodsId])->update(['stock' => DB::raw("stock + {$num}"), 'update_time' => time()]);
  601. }
  602. if ($skuId) {
  603. GoodsSkuModel::where(['id' => $skuId])->update(['stock' => DB::raw("stock + {$num}"), 'update_time' => time()]);
  604. }
  605. }
  606. }
  607. $this->error = '取消订单成功';
  608. $this->model->where(['user_id' => $userId, 'mark' => 0])->where('update_time', '<=', time() - 300)->delete();
  609. OrderGoodsModel::where(['order_no' => $orderNo, 'mark' => 0])->where('update_time', '<=', time() - 300)->delete();
  610. $this->model->where(['id' => $orderId])->update(['mark' => 0, 'update_time' => time()]);
  611. OrderGoodsModel::where(['order_no' => $orderNo])->update(['mark' => 0, 'update_time' => time()]);
  612. DB::commit();
  613. return ['id' => $orderId];
  614. }
  615. /**
  616. * 订单删除隐藏
  617. * @param $userId
  618. * @param $orderId
  619. * @return array|false
  620. */
  621. public function hide($userId, $orderId)
  622. {
  623. if ($orderId <= 0) {
  624. $this->error = '请选择订单';
  625. return false;
  626. }
  627. // 缓存锁
  628. $cacheLockKey = "caches:orders:hide_lock:{$userId}_{$orderId}";
  629. if (RedisService::get($cacheLockKey)) {
  630. $this->error = '订单删除中~';
  631. return false;
  632. }
  633. RedisService::set($cacheLockKey, ['order_id' => $orderId, 'user_id' => $userId], rand(3, 5));
  634. // 用户信息
  635. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  636. ->select(['id', 'openid', 'mobile', 'nickname', 'realname', 'balance', 'status'])
  637. ->first();
  638. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  639. if (empty($userInfo) || $status != 1) {
  640. $this->error = 1045;
  641. RedisService::clear($cacheLockKey);
  642. return false;
  643. }
  644. // 订单信息
  645. $info = $this->model->where(['id' => $orderId, 'mark' => 1])
  646. ->select(['id', 'order_no', 'pay_total', 'status'])
  647. ->first();
  648. $orderNo = isset($info['order_no']) ? $info['order_no'] : '';
  649. $status = isset($info['status']) ? $info['status'] : 0;
  650. if (empty($info) || empty($orderNo)) {
  651. $this->error = '订单信息不存在';
  652. RedisService::clear($cacheLockKey);
  653. return false;
  654. }
  655. if ($status != 4) {
  656. $this->error = '订单未完成';
  657. RedisService::clear($cacheLockKey);
  658. return false;
  659. }
  660. $this->error = '删除订单成功';
  661. $this->model->where(['id' => $orderId])->update(['is_hide' => 1, 'update_time' => time()]);
  662. return ['id' => $orderId];
  663. }
  664. /**
  665. * 订单完成
  666. * @param $userId 订单用户ID
  667. * @param $id 订单ID
  668. * @return array|false
  669. */
  670. public function complete($userId, $id, $check = true)
  671. {
  672. if ($id <= 0) {
  673. $this->error = '请选择订单';
  674. return false;
  675. }
  676. // 缓存锁
  677. $cacheLockKey = "caches:orders:complete_lock:{$userId}_{$id}";
  678. if (RedisService::get($cacheLockKey)) {
  679. $this->error = '订单处理中~';
  680. return false;
  681. }
  682. // 商品数据
  683. RedisService::set($cacheLockKey, ['order_id' => $id, 'user_id' => $userId], rand(3, 5));
  684. // 用户信息
  685. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  686. ->select(['id', 'openid', 'mobile', 'parent_id', 'nickname', 'realname', 'balance', 'status'])
  687. ->first();
  688. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  689. $parentId = isset($userInfo['parent_id']) ? $userInfo['parent_id'] : 0;
  690. if ($check && (empty($userInfo) || $status != 1)) {
  691. $this->error = 1045;
  692. RedisService::clear($cacheLockKey);
  693. return false;
  694. }
  695. // 订单信息
  696. $info = $this->model->with(['orderGoods','commission'])->where(['id' => $id, 'mark' => 1])
  697. ->select(['id', 'order_no','type', 'user_id', 'store_id', 'total', 'pay_total', 'delivery_no', 'delivery_company', 'delivery_code', 'status'])
  698. ->first();
  699. $orderNo = isset($info['order_no']) ? $info['order_no'] : '';
  700. $deliveryNo = isset($info['delivery_no']) ? $info['delivery_no'] : '';
  701. $deliverCompany = isset($info['delivery_company']) ? $info['delivery_company'] : '';
  702. $orderUserId = isset($info['user_id']) ? $info['user_id'] : 0;
  703. $storeId = isset($info['store_id']) ? $info['store_id'] : 0;
  704. $orderType = isset($info['type']) ? $info['type'] : 0;
  705. $orderTotal = isset($info['total']) ? $info['total'] : 0;
  706. $status = isset($info['status']) ? $info['status'] : 0;
  707. $commission = isset($info['commission']) ? $info['commission'] : [];
  708. $bonus = isset($commission['bonus'])?$commission['bonus'] : 0;
  709. $orderGoods = isset($info['order_goods']) ? $info['order_goods'] : [];
  710. if (empty($info) || empty($orderNo)) {
  711. $this->error = '订单信息不存在';
  712. RedisService::clear($cacheLockKey);
  713. return false;
  714. }
  715. if ($status != 3) {
  716. $this->error = '订单未发货';
  717. RedisService::clear($cacheLockKey);
  718. return false;
  719. }
  720. if (empty($deliveryNo) || empty($deliverCompany)) {
  721. $this->error = '订单发货信息错误,请联系客服';
  722. $this->model->where(['id' => $id])->update(['is_complete' => 1, 'complete_remark' => $this->error]);
  723. RedisService::clear("caches:orders:completeList");
  724. RedisService::clear($cacheLockKey);
  725. return false;
  726. }
  727. DB::beginTransaction();
  728. $completeStatus = env('ORDER_COMPLETE_STATUS', 5);
  729. $updateData = ['status' => $completeStatus, 'complete_at' => date('Y-m-d H:i:s'), 'update_time' => time()];
  730. if (!$check) {
  731. $updateData['is_complete'] = 1;
  732. $updateData['complete_remark'] = '自动收货';
  733. }
  734. $this->model->where(['id' => $id])->update($updateData);
  735. // 商家订单数据统计
  736. $updateData = ['order_count' => DB::raw('order_count+1'), 'order_total' => DB::raw("order_total + {$orderTotal}")];
  737. StoreModel::where(['id' => $storeId])->update($updateData);
  738. // 商品销量数据
  739. if ($orderGoods) {
  740. $counts = [];
  741. foreach ($orderGoods as $item) {
  742. $counts[$item['goods_id']] = isset($counts[$item['goods_id']]) ? $counts[$item['goods_id']] : 0;
  743. $counts[$item['goods_id']] += $item['num'];
  744. }
  745. if ($counts) {
  746. foreach ($counts as $id => $v) {
  747. GoodsModel::where(['id' => $id])->update(['sales' => DB::raw("sales + {$v}"), 'update_time' => time()]);
  748. }
  749. }
  750. }
  751. // 结算商家收益
  752. if ($bonus && SettleService::make()->storeBonus($storeId, $bonus, $info) < 0) {
  753. DB::rollBack();
  754. $this->error = SettleService::make()->getError();
  755. RedisService::clear($cacheLockKey);
  756. return false;
  757. }
  758. if($orderType==2){
  759. // 创业礼包结算
  760. if (SettleService::make()->businessBonus($orderUserId, $orderTotal, $commission, $info) < 0) {
  761. DB::rollBack();
  762. $this->error = SettleService::make()->getError();
  763. RedisService::clear($cacheLockKey);
  764. return false;
  765. }
  766. }else{
  767. // 商城奖励结算
  768. if (SettleService::make()->shopBonus($orderUserId, $orderTotal,$commission, $info) < 0) {
  769. DB::rollBack();
  770. $this->error = SettleService::make()->getError();
  771. RedisService::clear($cacheLockKey);
  772. return false;
  773. }
  774. }
  775. DB::commit();
  776. $this->error = '确认收货成功';
  777. RedisService::clear("caches:orders:completeList");
  778. RedisService::clear("caches:orders:revenueList");
  779. return ['id' => $id, 'msg' => $this->error];
  780. }
  781. /**
  782. * 售后或退款
  783. * @param $userId
  784. * @param $params
  785. * @return array|false
  786. */
  787. public function after($userId, $params)
  788. {
  789. $id = isset($params['id']) ? $params['id'] : 0;
  790. $afterType = isset($params['after_type']) ? $params['after_type'] : 1;
  791. if ($id <= 0) {
  792. $this->error = '请选择订单';
  793. return false;
  794. }
  795. // 缓存锁
  796. $cacheLockKey = "caches:orders:after_lock:{$userId}_{$id}";
  797. if (RedisService::get($cacheLockKey)) {
  798. $this->error = '订单处理中~';
  799. return false;
  800. }
  801. // 商品数据
  802. RedisService::set($cacheLockKey, ['params' => $params, 'user_id' => $userId], rand(3, 5));
  803. // 用户信息
  804. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  805. ->select(['id', 'openid', 'mobile', 'nickname', 'realname', 'balance', 'status'])
  806. ->first();
  807. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  808. if (empty($userInfo) || $status != 1) {
  809. $this->error = 1045;
  810. RedisService::clear($cacheLockKey);
  811. return false;
  812. }
  813. // 订单信息
  814. $info = $this->model->where(['id' => $id, 'mark' => 1])
  815. ->select(['id', 'order_no', 'after_type', 'refund_status', 'pay_total', 'status'])
  816. ->first();
  817. $orderNo = isset($info['order_no']) ? $info['order_no'] : '';
  818. $status = isset($info['status']) ? $info['status'] : 0;
  819. $refundStatus = isset($info['refund_status']) ? $info['refund_status'] : 0;
  820. if (empty($info) || empty($orderNo)) {
  821. $this->error = '订单信息不存在';
  822. RedisService::clear($cacheLockKey);
  823. return false;
  824. }
  825. if ($status == 1) {
  826. $this->error = '订单未支付';
  827. RedisService::clear($cacheLockKey);
  828. return false;
  829. }
  830. if ($status == 4 && $afterType == 2) {
  831. $this->error = '订单已完成';
  832. RedisService::clear($cacheLockKey);
  833. return false;
  834. }
  835. if ($refundStatus > 0 && $refundStatus != 4) {
  836. $this->error = '订单售后处理中';
  837. RedisService::clear($cacheLockKey);
  838. return false;
  839. }
  840. $afterRealname = isset($params['after_realname']) ? $params['after_realname'] : '';
  841. $afterPhone = isset($params['after_phone']) ? $params['after_phone'] : '';
  842. $afterRemark = isset($params['after_remark']) ? $params['after_remark'] : '';
  843. if ($afterType == 1) {
  844. if (empty($afterRealname) || empty($afterPhone) || empty($afterRemark)) {
  845. $this->error = '请填写售后信息';
  846. RedisService::clear($cacheLockKey);
  847. return false;
  848. }
  849. }
  850. $data = [
  851. 'after_type' => $afterType,
  852. 'after_realname' => $afterRealname,
  853. 'after_phone' => $afterPhone,
  854. 'after_remark' => $afterRemark,
  855. 'refund_remark' => isset($params['refund_remark']) ? $params['refund_remark'] : '',
  856. 'refund_status' => 3,
  857. 'update_time' => time()
  858. ];
  859. $this->model->where(['id' => $id])->update($data);
  860. $this->error = '订单申请售后成功';
  861. return ['id' => $id];
  862. }
  863. /**
  864. * 物流查询
  865. * @param $id
  866. * @return array|false|mixed
  867. */
  868. public function getDelivery($id)
  869. {
  870. $info = $this->model->where(['id' => $id, 'mark' => 1])->first();
  871. $deliveryNo = isset($info['delivery_no']) ? $info['delivery_no'] : '';
  872. $deliveryCode = isset($info['delivery_code']) ? $info['delivery_code'] : '';
  873. $mobile = isset($info['receiver_mobile']) ? $info['receiver_mobile'] : '';
  874. $receiverArea = isset($info['receiver_area']) && $info['receiver_area'] ? $info['receiver_area'] : '';
  875. if (empty($info)) {
  876. $this->error = '请选择订单';
  877. return false;
  878. }
  879. $cacheKey = "caches:kd100:order_{$id}";
  880. $data = RedisService::get($cacheKey);
  881. if ($data) {
  882. return $data;
  883. }
  884. $result = Kd100Service::make()->query($deliveryNo, $mobile, $deliveryCode, $receiverArea);
  885. RedisService::set($cacheKey . '_result', $result, 300);
  886. $status = isset($result['status']) ? $result['status'] : 0;
  887. $data = isset($result['data']) ? $result['data'] : [];
  888. $courierInfo = isset($result['courierInfo']) ? $result['courierInfo'] : [];
  889. $arrivalTime = isset($result['arrivalTime']) ? $result['arrivalTime'] : '';
  890. $predictedRoute = isset($result['predictedRoute']) ? $result['predictedRoute'] : [];
  891. $predictedData = $predictedRoute ? end($predictedRoute) : [];
  892. $arrivalData = [];
  893. if ($arrivalTime) {
  894. $arrivalData['arrivalTime'] = dayFormat(strtotime($arrivalTime . ':00:00'));
  895. $arrivalData['predictedData'] = $predictedData;
  896. }
  897. if ($courierInfo && $courierInfo['deliveryManPhone']) {
  898. $courierInfo['deliveryManPhone'] = explode(',', $courierInfo['deliveryManPhone']);
  899. $courierInfo['deliveryPhone'] = $courierInfo['deliveryManPhone'][1] ? $courierInfo['deliveryManPhone'][1] : $courierInfo['deliveryManPhone'][0];
  900. }
  901. if ($data && $status == 200) {
  902. RedisService::set($cacheKey, ['info' => $courierInfo, 'arrivalData' => $arrivalData, 'list' => $data], 1200);
  903. }
  904. return $data ? ['info' => $courierInfo, 'arrivalData' => $arrivalData, 'list' => $data] : [];
  905. }
  906. /**
  907. * 已发货待完成订单
  908. * @return array|mixed
  909. */
  910. public function getCompleteOrders()
  911. {
  912. $cacheKey = "caches:orders:completeList";
  913. $datas = RedisService::get($cacheKey);
  914. if ($datas) {
  915. return $datas;
  916. }
  917. $completeDay = ConfigService::make()->getConfigByCode('order_complete_day', 7);
  918. $limitNum = ConfigService::make()->getConfigByCode('order_complete_batch_num', 300);
  919. $limitNum = $limitNum > 10 && $limitNum < 2000 ? $limitNum : 300;
  920. $completeDay = $completeDay >= 1 && $completeDay < 30 ? $completeDay : 7;
  921. $datas = $this->model->where(['status' => 3, 'is_complete' => 2, 'mark' => 1])
  922. ->whereNotNull('delivery_no')
  923. ->select(['id', 'user_id', 'order_no', 'status'])
  924. ->where('pay_at', '<=', date('Y-m-d H:i:s', time() - $completeDay * 86400))
  925. ->limit($limitNum)
  926. ->get();
  927. $datas = $datas ? $datas->toArray() : [];
  928. if ($datas) {
  929. RedisService::set($cacheKey, $datas, rand(300, 600));
  930. }
  931. return $datas;
  932. }
  933. /**
  934. * 已完成,待分账订单
  935. * @return array|mixed
  936. */
  937. public function getRevenueOrderList()
  938. {
  939. $cacheKey = "caches:orders:revenueList";
  940. $datas = RedisService::get($cacheKey);
  941. if ($datas) {
  942. return $datas;
  943. }
  944. $limitNum = ConfigService::make()->getConfigByCode('order_revenue_batch_num', 300);
  945. $limitNum = $limitNum > 10 && $limitNum < 2000 ? $limitNum : 300;
  946. $datas = $this->model->where(['status' => 4, 'is_revenue' => 1, 'revenue_status' => 2, 'mark' => 1])
  947. ->select(['id', 'user_id', 'pay_total', 'order_no', 'revenue_no', 'transaction_id', 'status'])
  948. ->limit($limitNum)
  949. ->get();
  950. $datas = $datas ? $datas->toArray() : [];
  951. if ($datas) {
  952. RedisService::set($cacheKey, $datas, rand(300, 600));
  953. }
  954. return $datas;
  955. }
  956. /**
  957. * 订单分账处理
  958. * @param $id
  959. * @return false
  960. * @throws \Yansongda\Pay\Exception\ContainerException
  961. * @throws \Yansongda\Pay\Exception\InvalidParamsException
  962. */
  963. public function revenue($id)
  964. {
  965. if ($id <= 0) {
  966. $this->error = '订单参数错误';
  967. return false;
  968. }
  969. // 缓存锁
  970. $cacheLockKey = "caches:orders:revenue_lock:{$id}";
  971. if (RedisService::get($cacheLockKey)) {
  972. $this->error = '订单分账处理中~';
  973. return false;
  974. }
  975. // 是否设置分账账户
  976. $revenueOpenid = ConfigService::make()->getConfigByCode('order_revenue_openid', '');
  977. if (empty($revenueOpenid)) {
  978. $this->error = '订单分账账户未配置';
  979. return false;
  980. }
  981. // 订单信息
  982. RedisService::set($cacheLockKey, ['id' => $id, 'date' => date('Y-m-d H:i:s')], 20);
  983. $info = $this->model->where(['id' => $id, 'mark' => 1])
  984. ->select(['id', 'order_no', 'revenue_no', 'user_id', 'transaction_id', 'pay_total', 'is_revenue', 'revenue_status', 'revenue_amount', 'status'])
  985. ->first();
  986. $revenueOrderNo = isset($info['revenue_no']) ? $info['revenue_no'] : '';
  987. $revenueAmount = isset($info['revenue_amount']) ? $info['revenue_amount'] : 0;
  988. $status = isset($info['status']) ? $info['status'] : 0;
  989. $isRevenue = isset($info['is_revenue']) ? $info['is_revenue'] : 0;
  990. $revenueStatus = isset($info['revenue_status']) ? $info['revenue_status'] : 0;
  991. if ($status != 4) {
  992. RedisService::clear($cacheLockKey);
  993. $this->error = '订单状态错误,未完成收货的订单无法分账';
  994. return false;
  995. }
  996. if ($isRevenue != 1) {
  997. RedisService::clear($cacheLockKey);
  998. $this->error = '该订单不是分账订单';
  999. return false;
  1000. }
  1001. if ($revenueStatus != 2) {
  1002. RedisService::clear($cacheLockKey);
  1003. $this->error = '该订单分账已处理完成';
  1004. return false;
  1005. }
  1006. if ($revenueAmount <= 0) {
  1007. RedisService::clear($cacheLockKey);
  1008. $this->error = '订单分账金额不足';
  1009. return false;
  1010. }
  1011. $order = [
  1012. 'transaction_id' => $info['transaction_id'],
  1013. 'out_order_no' => $revenueOrderNo,
  1014. 'body' => '订单分账',
  1015. 'amount' => $revenueAmount,
  1016. 'unsplit' => true, // 只分一次
  1017. ];
  1018. $result = PaymentService::make()->profitsharing($revenueOpenid, $order);
  1019. $state = isset($result->state) ? $result->state : 0;
  1020. $message = isset($result->message) ? $result->message : '分账失败';
  1021. $orderId = isset($result->order_id) ? $result->order_id : '';
  1022. if ($state == 'FINISHED') {
  1023. $this->model->where(['id' => $id])->update(['revenue_status' => 1, 'revenue_order_id' => $orderId, 'update_time' => time()]);
  1024. RedisService::clear($cacheLockKey);
  1025. RedisService::clear("caches:orders:revenueList");
  1026. $this->error = '分账处理成功';
  1027. return true;
  1028. } else {
  1029. RedisService::clear($cacheLockKey);
  1030. $this->error = $message;
  1031. return false;
  1032. }
  1033. }
  1034. }