OrderService.php 59 KB

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