OrderService.php 56 KB

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