OrderService.php 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454
  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\CartsModel;
  14. use App\Models\GoodsModel;
  15. use App\Models\MemberCouponModel;
  16. use App\Models\MemberModel;
  17. use App\Models\MerchantModel;
  18. use App\Models\OrderGoodsModel;
  19. use App\Models\OrderModel;
  20. use App\Services\BaseService;
  21. use App\Services\ConfigService;
  22. use App\Services\RedisService;
  23. use App\Services\SupplyService;
  24. use Illuminate\Support\Facades\DB;
  25. /**
  26. * 订单管理-服务类
  27. * @author laravel开发员
  28. * @since 2020/11/11
  29. * Class OrderService
  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. * OrderService constructor.
  41. */
  42. public function __construct()
  43. {
  44. $this->model = new OrderModel();
  45. }
  46. /**
  47. * 静态入口
  48. * @return static|null
  49. */
  50. public static function make()
  51. {
  52. if (!self::$instance) {
  53. self::$instance = (new static());
  54. }
  55. return self::$instance;
  56. }
  57. /**
  58. * @param $params
  59. * @param int $pageSize
  60. * @return array
  61. */
  62. public function getDataList($params, $pageSize = 15)
  63. {
  64. $where = ['a.mark' => 1,'a.is_hide'=>0];
  65. $merchId = isset($params['merch_id']) ? $params['merch_id'] : 0;
  66. if ($merchId > 0) {
  67. $where['a.merch_id'] = $merchId;
  68. }
  69. $merchUid = isset($params['merch_uid']) ? $params['merch_uid'] : 0;
  70. if ($merchUid > 0) {
  71. $where['a.merch_uid'] = $merchUid;
  72. }
  73. $list = $this->model->from('orders as a')->with(['goods'])
  74. ->leftJoin('member as b', 'a.user_id', '=', 'b.id')
  75. ->where($where)
  76. ->where(function ($query) use ($params) {
  77. $keyword = isset($params['kw']) ? $params['kw'] : '';
  78. if ($keyword) {
  79. $query->where('a.order_no', 'like', "%{$keyword}%")->orWhere('b.id', '=', "{$keyword}")->orWhere('b.nickname', 'like', "%{$keyword}%")->orWhere('b.mobile', 'like', "%{$keyword}%");
  80. }
  81. })
  82. ->where(function ($query) use ($params) {
  83. $status = isset($params['status']) ? $params['status'] : 0;
  84. $userId = isset($params['user_id']) ? $params['user_id'] : 0;
  85. $type = isset($params['type']) ? $params['type'] : 0;
  86. if ($userId) {
  87. $query->where('a.user_id', '=', $userId);
  88. }
  89. if ($type > 0) {
  90. $query->where('a.type', '=', $type);
  91. }
  92. if ($status > 0) {
  93. $query->where('a.status', '=', $status);
  94. }else{
  95. $query->where('a.status', '>', 1);
  96. }
  97. })
  98. ->select(['a.*', 'b.nickname', 'b.trc_url'])
  99. ->orderBy('a.pay_time', 'desc')
  100. ->orderBy('a.id', 'desc')
  101. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  102. $list = $list ? $list->toArray() : [];
  103. if ($list) {
  104. $refundStatusArr = [1=>'退款中',2=>'已退款',3=>'退款失败'];
  105. $statusArr = [1=>'待付款',2=>'待发货',3=>'待收货',4=>'已完成',5=>'已售后'];
  106. $supplyList = config('goods.supplyList');
  107. foreach ($list['data'] as &$item) {
  108. $item['create_time'] = $item['create_time'] ? datetime($item['create_time'], 'Y-m-d H:i:s') : '';
  109. $item['pay_time'] = $item['pay_time'] ? datetime($item['pay_time'], 'Y-m-d H:i:s') : '';
  110. $status = isset($item['status'])? $item['status'] : 0;
  111. $item['status_text'] = '待付款';
  112. $item['refund_status_text'] = '';
  113. if($status){
  114. if($item['type'] == 2){
  115. $item['status_text'] = isset($serviceStatusArr[$status])? $serviceStatusArr[$status] : '';
  116. }else{
  117. $item['status_text'] = isset($statusArr[$status])? $statusArr[$status] : '';
  118. }
  119. }
  120. $refundStatus = isset($item['refund_status'])? $item['refund_status'] : 0;
  121. if($refundStatus && $status != 4){
  122. $item['refund_status_text'] = isset($refundStatusArr[$refundStatus])? $refundStatusArr[$refundStatus] : '';
  123. }
  124. $goods = isset($item['goods'])? $item['goods'] : [];
  125. if($goods){
  126. foreach ($goods as &$v){
  127. $v['supply_name'] = isset($supplyList[$v['supply_type']]) ? $supplyList[$v['supply_type']] : '';
  128. $v['main_img'] = isset($v['main_img']) && $v['main_img']? get_image_url($v['main_img']) : '';
  129. $v['sku_attr'] = isset($v['sku_attr']) && $v['sku_attr']? json_decode($v['sku_attr'], true) : [];
  130. }
  131. unset($v);
  132. }
  133. $item['goods'] = $goods? $goods : [];
  134. }
  135. unset($item);
  136. }
  137. return [
  138. 'pageSize' => $pageSize,
  139. 'total' => isset($list['total']) ? $list['total'] : 0,
  140. 'counts' => [],
  141. 'list' => isset($list['data']) ? $list['data'] : []
  142. ];
  143. }
  144. /**
  145. * 购买商品
  146. * @param $userId 用户ID
  147. * @param $params
  148. * @return array|false
  149. */
  150. public function buySubmit($userId, $params)
  151. {
  152. $payType = isset($params['pay_type'])? intval($params['pay_type']) : 0;
  153. $type = isset($params['type']) && $params['type']? intval($params['type']) : 1;
  154. $amount = isset($params['total']) && $params['total']? floatval($params['total']) : 0;
  155. $couponId = isset($params['coupon_id'])? intval($params['coupon_id']) : 0;
  156. $addressId = isset($params['address_id'])? intval($params['address_id']) : 0;
  157. $freightAddressId = isset($params['freight_address_id'])? intval($params['freight_address_id']) : 0;
  158. $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
  159. $skuList = isset($params['sku_list'])? $params['sku_list'] : [];
  160. $ids = isset($params['ids'])? $params['ids'] : [];
  161. $cartIds = isset($params['cart_ids'])? trim($params['cart_ids']) : '';
  162. $cartIds = $cartIds? explode('|', $cartIds) : [];
  163. if(empty($skuList) || empty($ids) || $addressId<=0 || $freightAddressId<=0 || $payType<=0){
  164. $this->error = 2420;
  165. return false;
  166. }
  167. // 锁
  168. $cacheKey = "caches:orders:buy:{$userId}";
  169. if(RedisService::get($cacheKey)){
  170. $this->error = 1053;
  171. return false;
  172. }
  173. // 订单商品
  174. $goods = GoodsService::make()->getOrderGoods($userId, $ids);
  175. if(empty($goods)){
  176. $this->error = 2903;
  177. return false;
  178. }
  179. // 格式化
  180. $skuArr = [];
  181. $skuAttr = [];
  182. foreach ($skuList as $v){
  183. $skuArr[$v['goods_id']] = [
  184. 'sku_id'=> $v['sku_id'],
  185. 'num'=> $v['num'],
  186. ];
  187. $skuAttr[$v['goods_id']] = $v['attr'];
  188. }
  189. $skuList = $skuArr;
  190. $goodsNum = 0;
  191. $orderTotal = 0;
  192. $orderXdTotal = 0;
  193. $merchId = 0;
  194. $orderNo = get_order_num('XS');
  195. // 价格参数
  196. $usdtPrice = RedisService::get("caches:wallets:usdt_rate");
  197. if($usdtPrice<=0){
  198. $usdtCnyPrice = ConfigService::make()->getConfigByCode('usdt_cny_price', 7.2);
  199. $usdtPrice = $usdtCnyPrice>0 && $usdtCnyPrice< 100? $usdtCnyPrice : 0;
  200. }
  201. $xdPrice = ConfigService::make()->getConfigByCode('xd_price', 100);
  202. $xdPrice = $xdPrice > 0 && $xdPrice <= 10000 ? $xdPrice : 100;
  203. foreach($goods as &$item){
  204. $goodsId = isset($item['goods_id'])? $item['goods_id'] : 0;
  205. $merchId = isset($item['merch_id'])? $item['merch_id'] : 0;
  206. $retailPrice = isset($item['retail_price'])? $item['retail_price'] : 0;
  207. $num = isset($skuList[$goodsId]['num'])? intval($skuList[$goodsId]['num']) : 0;
  208. $skuId = isset($skuList[$goodsId]['sku_id'])? intval($skuList[$goodsId]['sku_id']) : 0;
  209. $attr = isset($skuAttr[$goodsId])? $skuAttr[$goodsId] : [];
  210. if($num>0 && $skuId >0 && $retailPrice>0){
  211. $item['price'] = moneyFormat($retailPrice/$usdtPrice * $xdPrice,2);
  212. $total = moneyFormat($retailPrice * $num, 2);
  213. $xdTotal = moneyFormat($item['price'] * $num, 2);
  214. // 订单商品
  215. $item['order_no'] = $orderNo;
  216. $item['total'] = $total;
  217. $item['xd_total'] = $xdTotal;
  218. $item['num'] = $num;
  219. $item['sku_attr'] = $attr? json_encode($attr, 256) : '';
  220. $item['create_time'] = time();
  221. $item['update_time'] = time();
  222. $item['status'] = 1;
  223. $item['mark'] = 1;
  224. // 订单金额
  225. $orderTotal += $total;
  226. $orderXdTotal += $xdTotal;
  227. $goodsNum += $num;
  228. }
  229. }
  230. unset($item);
  231. if($orderXdTotal<=0 || $goodsNum<=0){
  232. $this->error = 2904;
  233. return false;
  234. }
  235. // 优惠券
  236. $couponPrice = 0;
  237. if($couponId > 0){
  238. }
  239. // 验证用户
  240. $userInfo = MemberModel::where(['id'=> $userId,'mark'=> 1,'status'=> 1])
  241. ->select(['id','nickname','pay_password','balance','parent_id','parents'])
  242. ->first();
  243. $userInfo = $userInfo? $userInfo->toArray() : [];
  244. $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
  245. $userXd = isset($userInfo['balance'])? floatval($userInfo['balance']) : 0.00;
  246. if(empty($userInfo)){
  247. $this->error = 2024;
  248. return false;
  249. }
  250. // 余额支付支付密码验证
  251. if($payType == 10 && empty($userPayPassword)){
  252. $this->error =1040;
  253. return false;
  254. }
  255. // 星豆余额支付交易密码
  256. $payPassword = get_password($payPassword);
  257. if($payType == 10 && $payPassword != $userPayPassword){
  258. $this->error = 2038;
  259. return false;
  260. }
  261. // 运费
  262. $skus = array_values($skuList);
  263. if(!$freightData = GoodsService::make()->getFreight($userId, $freightAddressId, $skus)){
  264. $this->error = GoodsService::make()->getError()?? 2905;
  265. return false;
  266. }
  267. $freight = isset($freightData['freight'])? floatval($freightData['freight']) : 0;
  268. $payTotal = moneyFormat($orderXdTotal+$freight,2);
  269. //var_dump($payTotal, $amount);
  270. if(intval($amount) != intval($payTotal)){
  271. $this->error ='2906';
  272. return false;
  273. }
  274. // 星豆余额支付验证
  275. if($payType == 10 && $userXd < $payTotal){
  276. $this->error = 2304;
  277. return false;
  278. }
  279. // 收货地址
  280. $addressInfo = MemberAddressService::make()->getBindInfo($userId, $addressId);
  281. $addressText = isset($addressInfo['address_text'])? $addressInfo['address_text'] : '';
  282. $city = isset($addressInfo['city'])? $addressInfo['city'] : '';
  283. $realname = isset($addressInfo['realname'])? $addressInfo['realname'] : '';
  284. $mobile = isset($addressInfo['mobile'])? $addressInfo['mobile'] : '';
  285. $address = isset($addressInfo['address'])? $addressInfo['address'] : '';
  286. if(empty($addressText) || empty($addressInfo) || empty($realname) || empty($mobile)){
  287. $this->error = 2902;
  288. return false;
  289. }
  290. $merchUId = 0;
  291. // 奖励待返积分
  292. $waitScoreRate = ConfigService::make()->getConfigByCode('shop_award_score_rate',0);
  293. $waitScoreRate = $waitScoreRate>=0 && $waitScoreRate<=1000? $waitScoreRate : 0;
  294. $awardWaitScore = moneyFormat($orderXdTotal * $waitScoreRate/100, 2);
  295. // 算力奖励
  296. $powerRate = ConfigService::make()->getConfigByCode('shop_award_power_rate',0);
  297. $powerRate = $powerRate>=0 && $powerRate<=1000? $powerRate : 0;
  298. $awardPowerNum = moneyFormat($orderXdTotal * $powerRate/100, 2);
  299. // 订单数据
  300. $order = [
  301. 'user_id'=> $userId,
  302. 'order_no'=> $orderNo,
  303. 'merch_id'=> $merchId,
  304. 'merch_uid'=> $merchUId,
  305. 'type'=> $type,
  306. 'price'=> 0.00,
  307. 'xd_price'=> $xdPrice,
  308. 'num'=> $goodsNum,
  309. 'city'=> $city,
  310. 'real_name'=> $realname,
  311. 'mobile'=> $mobile,
  312. 'address'=> $address && $addressText? $addressText.' '.$address : $addressText,
  313. 'total'=> $orderTotal,
  314. 'xd_total'=> $orderXdTotal,
  315. 'pay_type'=> $payType,
  316. 'pay_money'=> $payTotal,
  317. 'delivery_type'=> 1,
  318. 'coupon_id'=> $couponId,
  319. 'coupon_price'=> $couponPrice,
  320. 'postage'=> $freight,
  321. 'award_wait_score'=> $awardWaitScore,
  322. 'award_power_num'=> $awardPowerNum,
  323. 'create_time'=> time(),
  324. 'update_time'=> time(),
  325. 'remark'=> isset($params['remark'])? trim($params['remark']) : '',
  326. 'status'=> 1,
  327. 'mark'=> 1,
  328. ];
  329. // 站外订单提交
  330. RedisService::set($cacheKey, $order, rand(2,3));
  331. $orderParams = [
  332. 'third_order'=> $orderNo,
  333. 'address_id'=> $freightAddressId,
  334. 'sku_list'=> $skus,
  335. 'receiver'=> $realname,
  336. 'receiver_phone'=> $mobile,
  337. 'address'=> $address,
  338. 'other'=> isset($params['remark'])? $params['remark'] : '',
  339. ];
  340. $result = SupplyService::make()->getApiData('orderSubmit', $orderParams);
  341. $outOrderNo = isset($result['out_order_no'])? $result['out_order_no'] : '';
  342. $expense = isset($result['expense'])? floatval($result['expense']) : 0;
  343. $servicePrice = isset($result['service_price'])? floatval($result['service_price']) : 0;
  344. if(empty($result)){
  345. RedisService::clear($cacheKey);
  346. $this->error = SupplyService::make()->getError();
  347. return false;
  348. }
  349. // 创建订单
  350. $order['out_order_no'] = $outOrderNo;
  351. $order['expense'] = $expense;
  352. $order['service_price'] = $servicePrice;
  353. if(!$orderId = $this->model->insertGetId($order)){
  354. $this->error = 2907;
  355. RedisService::clear($cacheKey);
  356. return false;
  357. }
  358. // 写入订单商品
  359. if($orderId && !OrderGoodsModel::insert($goods)){
  360. $this->error = 2908;
  361. RedisService::clear($cacheKey);
  362. return false;
  363. }
  364. DB::beginTransaction();
  365. // 支付处理
  366. $payment = [];
  367. $dateTime = date('Y-m-d H:i:s');
  368. switch($payType){
  369. case 10: // 星豆余额支付
  370. // 扣除余额
  371. $updateData = [
  372. 'usdt'=> DB::raw("usdt - {$payTotal}"), // 扣除USDT
  373. 'update_time'=>time()
  374. ];
  375. if(!MemberModel::where(['id'=> $userId])->update($updateData)){
  376. DB::rollBack();
  377. $this->error = 1042;
  378. RedisService::clear($cacheKey);
  379. return false;
  380. }
  381. // 余额明细
  382. $log = [
  383. 'user_id' => $userId,
  384. 'source_id' => $orderId,
  385. 'source_order_no' => $orderNo,
  386. 'type' => 3,
  387. 'coin_type' => 2,
  388. 'user_type'=> 1,
  389. 'money' => $payTotal,
  390. 'actual_money' => $payTotal,
  391. 'balance' => $userXd,
  392. 'create_time' => time(),
  393. 'update_time' => time(),
  394. 'remark' => "商城购物消费",
  395. 'status' => 1,
  396. 'mark' => 1,
  397. ];
  398. if(!AccountLogModel::insertGetId($log)){
  399. DB::rollBack();
  400. $this->error = 2029;
  401. RedisService::clear($cacheKey);
  402. return false;
  403. }
  404. // 更新订单状态
  405. $updateData = ['status'=>2,'pay_status'=> 1,'pay_time'=>date('Y-m-d H:i:s'),'update_time'=>time()];
  406. if(!$this->model->where(['id'=> $orderId,'mark'=>1])->update($updateData)){
  407. DB::rollBack();
  408. $this->error = 2909;
  409. RedisService::clear($cacheKey);
  410. return false;
  411. }
  412. $payStatus = 1;
  413. break;
  414. default:
  415. $this->error = 1030;
  416. return false;
  417. }
  418. // 更新优惠券状态
  419. if($couponId>0 && !MemberCouponModel::where(['id'=> $couponId,'mark'=>1])->update(['status'=> 2,'update_time'=>time()])){
  420. DB::rollBack();
  421. $this->error = 2908;
  422. RedisService::clear($cacheKey);
  423. return false;
  424. }
  425. // 购物车处理
  426. if($cartIds){
  427. CartsModel::where(['user_id'=> $userId,'status'=>1,'mark'=>1])
  428. ->whereIn('id', $cartIds)
  429. ->update(['status'=>2,'update_time'=>time()]);
  430. }
  431. // 已支付
  432. RedisService::clear($cacheKey);
  433. if($payStatus == 1){
  434. // 支付成功订单通知
  435. $message = "您在{$dateTime}(UTC+8)创建的订单【{$orderNo}】,金额{$payTotal}星豆,已支付成功,请耐心等候发货。";
  436. MessageService::make()->pushMessage($userId,"订单支付成功",$message, 2);
  437. DB::commit();
  438. $this->error = 2910;
  439. return [
  440. 'id'=> $orderId,
  441. 'out_order_no'=> $outOrderNo,
  442. 'total'=> $payTotal,
  443. 'pay_type'=> $payType,
  444. ];
  445. }else{
  446. // 下单成功订单通知
  447. $message = "您在{$dateTime}(UTC+8)创建订单【{$orderNo}】成功,请尽快完成支付。";
  448. MessageService::make()->pushMessage($userId,"订单创建成功",$message, 2);
  449. DB::commit();
  450. $this->error = 2911;
  451. return [
  452. 'id'=> $orderId,
  453. 'out_order_no'=> $outOrderNo,
  454. 'total'=> $payTotal,
  455. 'pay_type'=> $payType,
  456. ];
  457. }
  458. }
  459. /**
  460. * 购买商品
  461. * @param $userId 用户ID
  462. * @param $params
  463. * @return array|false
  464. */
  465. public function buySubmit1($userId, $params)
  466. {
  467. $payType = isset($params['pay_type'])? intval($params['pay_type']) : 0;
  468. $type = isset($params['type']) && $params['type']? intval($params['type']) : 1;
  469. $amount = isset($params['total']) && $params['total']? floatval($params['total']) : 0;
  470. $couponId = isset($params['coupon_id'])? intval($params['coupon_id']) : 0;
  471. $addressId = isset($params['address_id'])? intval($params['address_id']) : 0;
  472. $freightAddressId = isset($params['freight_address_id'])? intval($params['freight_address_id']) : 0;
  473. $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
  474. $skuList = isset($params['sku_list'])? $params['sku_list'] : [];
  475. $ids = isset($params['ids'])? $params['ids'] : [];
  476. $cartIds = isset($params['cart_ids'])? trim($params['cart_ids']) : '';
  477. $cartIds = $cartIds? explode('|', $cartIds) : [];
  478. if(empty($skuList) || empty($ids) || $addressId<=0 || $freightAddressId<=0 || $payType<=0){
  479. $this->error = 2420;
  480. return false;
  481. }
  482. // 锁
  483. $cacheKey = "caches:orders:buy:{$userId}";
  484. if(RedisService::get($cacheKey)){
  485. $this->error = 1053;
  486. return false;
  487. }
  488. // 订单商品
  489. $goods = GoodsService::make()->getOrderGoods($userId, $ids);
  490. if(empty($goods)){
  491. $this->error = 2903;
  492. return false;
  493. }
  494. $goodsNum = 0;
  495. $orderTotal = 0;
  496. $orderXdTotal = 0;
  497. $merchId = 0;
  498. $goods = [];
  499. $orderNo = get_order_num('XS');
  500. // 价格参数
  501. $usdtPrice = RedisService::get("caches:wallets:usdt_rate");
  502. if($usdtPrice<=0){
  503. $usdtCnyPrice = ConfigService::make()->getConfigByCode('usdt_cny_price', 7.2);
  504. $usdtPrice = $usdtCnyPrice>0 && $usdtCnyPrice< 100? $usdtCnyPrice : 0;
  505. }
  506. $xdPrice = ConfigService::make()->getConfigByCode('xd_price', 100);
  507. $xdPrice = $xdPrice > 0 && $xdPrice <= 10000 ? $xdPrice : 100;
  508. foreach($goods as &$item){
  509. $goodsId = isset($item['goods_id'])? $item['goods_id'] : 0;
  510. $merchId = isset($item['merch_id'])? $item['merch_id'] : 0;
  511. $retailPrice = isset($item['retail_price'])? $item['retail_price'] : 0;
  512. $num = isset($skuList[$goodsId]['num'])? intval($skuList[$goodsId]['num']) : 0;
  513. $skuId = isset($skuList[$goodsId]['sku_id'])? intval($skuList[$goodsId]['sku_id']) : 0;
  514. if($num>0 && $skuId >0 && $retailPrice>0){
  515. $item['price'] = moneyFormat($retailPrice/$usdtPrice * $xdPrice,2);
  516. $total = moneyFormat($retailPrice * $num, 2);
  517. $xdTotal = moneyFormat($item['price'] * $num, 2);
  518. // 订单商品
  519. $item['order_no'] = $orderNo;
  520. $item['total'] = $total;
  521. $item['xd_total'] = $xdTotal;
  522. $item['num'] = $num;
  523. $item['create_time'] = time();
  524. $item['update_time'] = time();
  525. $item['status'] = 1;
  526. $item['mark'] = 1;
  527. // 订单金额
  528. $orderTotal += $total;
  529. $orderXdTotal += $xdTotal;
  530. $goodsNum += $num;
  531. }
  532. }
  533. if($orderXdTotal<=0 || $goodsNum<=0){
  534. $this->error ='2904';
  535. return false;
  536. }
  537. // 优惠券
  538. $couponPrice = 0;
  539. if($couponId > 0){
  540. }
  541. // 运费
  542. $skus = array_values($skuList);
  543. if(!$freightData = GoodsService::make()->getFreight($userId, $freightAddressId, $skus)){
  544. $this->error ='2905';
  545. return false;
  546. }
  547. $freight = isset($freightData['freight'])? floatval($freightData['freight']) : 0;
  548. $payTotal = moneyFormat($orderXdTotal+$freight,2);
  549. if($amount != $payTotal){
  550. $this->error ='2906';
  551. return false;
  552. }
  553. // 验证用户
  554. $userInfo = MemberModel::with(['parent'])->where(['id'=> $userId,'mark'=> 1,'status'=> 1])
  555. ->select(['id','nickname','pay_password','balance','usdt','power_num','wait_score','parent_id','parents'])
  556. ->first();
  557. $userInfo = $userInfo? $userInfo->toArray() : [];
  558. $parentInfo = isset($userInfo['parent'])? $userInfo['parent'] : [];
  559. $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
  560. $userXd = isset($userInfo['balance'])? floatval($userInfo['balance']) : 0.00;
  561. $userWaitScore = isset($userInfo['wait_score'])? floatval($userInfo['wait_score']) : 0.00;
  562. $userPowerNum = isset($userInfo['power_num'])? floatval($userInfo['power_num']) : 0.00;
  563. if(empty($userInfo)){
  564. $this->error = 2024;
  565. return false;
  566. }
  567. // 余额支付支付密码验证
  568. if($payType == 10 && empty($userPayPassword)){
  569. $this->error =1040;
  570. return false;
  571. }
  572. // 星豆余额支付交易密码
  573. $payPassword = get_password($payPassword);
  574. if($payType == 10 && $payPassword != $userPayPassword){
  575. $this->error = 2038;
  576. return false;
  577. }
  578. // 星豆余额支付验证
  579. if($payType == 10 && $userXd < $payTotal){
  580. $this->error = 2304;
  581. return false;
  582. }
  583. // 收货地址
  584. $addressInfo = MemberAddressService::make()->getBindInfo($userId, $addressId);
  585. $addressText = isset($addressInfo['address_text'])? $addressInfo['address_text'] : '';
  586. $city = isset($addressInfo['city'])? $addressInfo['city'] : '';
  587. $realname = isset($addressInfo['realname'])? $addressInfo['realname'] : '';
  588. $mobile = isset($addressInfo['mobile'])? $addressInfo['mobile'] : '';
  589. $address = isset($addressInfo['address'])? $addressInfo['address'] : '';
  590. if(empty($addressText) || empty($addressInfo) || empty($realname) || empty($mobile)){
  591. $this->error = 2902;
  592. return false;
  593. }
  594. $merchUId = 0;
  595. // 奖励待返积分
  596. $waitScoreRate = ConfigService::make()->getConfigByCode('shop_award_score_rate',0);
  597. $waitScoreRate = $waitScoreRate>=0 && $waitScoreRate<=1000? $waitScoreRate : 0;
  598. $awardWaitScore = moneyFormat($orderXdTotal * $waitScoreRate/100, 2);
  599. // 算力奖励
  600. $powerRate = ConfigService::make()->getConfigByCode('shop_award_power_rate',0);
  601. $powerRate = $powerRate>=0 && $powerRate<=1000? $powerRate : 0;
  602. $awardPowerNum = moneyFormat($orderXdTotal * $powerRate/100, 2);
  603. // 订单数据
  604. $order = [
  605. 'user_id'=> $userId,
  606. 'order_no'=> $orderNo,
  607. 'merch_id'=> $merchId,
  608. 'merch_uid'=> $merchUId,
  609. 'type'=> $type,
  610. 'price'=> 0.00,
  611. 'xd_price'=> $xdPrice,
  612. 'num'=> $goodsNum,
  613. 'city'=> $city,
  614. 'real_name'=> $realname,
  615. 'mobile'=> $mobile,
  616. 'address'=> $address && $addressText? $addressText.' '.$address : $addressText,
  617. 'total'=> $orderTotal,
  618. 'xd_total'=> $orderXdTotal,
  619. 'pay_type'=> $payType,
  620. 'pay_money'=> $payTotal,
  621. 'delivery_type'=> 1,
  622. 'coupon_id'=> $couponId,
  623. 'coupon_price'=> $couponPrice,
  624. 'postage'=> $freight,
  625. 'award_wait_score'=> $awardWaitScore,
  626. 'award_power_num'=> $awardPowerNum,
  627. 'create_time'=> time(),
  628. 'update_time'=> time(),
  629. 'remark'=> isset($params['remark'])? trim($params['remark']) : '',
  630. 'status'=> 1,
  631. 'mark'=> 1,
  632. ];
  633. // 创建订单
  634. DB::beginTransaction();
  635. RedisService::set($cacheKey, $order, rand(2,3));
  636. if(!$orderId = $this->model->insertGetId($order)){
  637. DB::rollBack();
  638. $this->error = 2907;
  639. RedisService::clear($cacheKey);
  640. return false;
  641. }
  642. // 写入订单商品
  643. if(!OrderGoodsModel::insert($goods)){
  644. DB::rollBack();
  645. $this->error = 2908;
  646. RedisService::clear($cacheKey);
  647. return false;
  648. }
  649. // 支付处理
  650. $payment = [];
  651. $payStatus = 2;
  652. $userAwardWaitScore = 0;
  653. $inviteAwardWaitScore = 0;
  654. $parentId = isset($parentInfo['id'])? $parentInfo['id'] : 0;
  655. $dateTime = date('Y-m-d H:i:s');
  656. switch($payType){
  657. case 10: // 星豆余额支付
  658. // 推荐用户奖励
  659. $parentStatus = isset($parentInfo['status'])? $parentInfo['status'] : 0;
  660. if($parentInfo && $parentStatus==1 && $awardWaitScore>0){
  661. // 奖励上级待返积分
  662. $inviteWaitScoreRate = ConfigService::make()->getConfigByCode('cost_award_invite_wait_score',0);
  663. $inviteWaitScoreRate = $inviteWaitScoreRate>0 && $inviteWaitScoreRate<100? $inviteWaitScoreRate : 0;
  664. $inviteAwardWaitScore = moneyFormat($awardWaitScore * $inviteWaitScoreRate/100, 2);
  665. $userAwardWaitScore = moneyFormat($awardWaitScore - $inviteAwardWaitScore, 2);
  666. }
  667. // 扣除余额
  668. $updateData = [
  669. 'usdt'=> DB::raw("usdt - {$payTotal}"), // 扣除USDT
  670. // 'wait_score'=>DB::raw("wait_score + {$userAwardWaitScore}"), // 用户待返积分奖励
  671. // 'power_num'=>DB::raw("power_num + {$awardPowerNum}"), // 算力奖励
  672. 'update_time'=>time()
  673. ];
  674. if(!MemberModel::where(['id'=> $userId])->update($updateData)){
  675. DB::rollBack();
  676. $this->error = 1042;
  677. RedisService::clear($cacheKey);
  678. return false;
  679. }
  680. // 余额明细
  681. $log = [
  682. 'user_id' => $userId,
  683. 'source_id' => $orderId,
  684. 'source_order_no' => $orderNo,
  685. 'type' => 3,
  686. 'coin_type' => 2,
  687. 'user_type'=> 1,
  688. 'money' => $payTotal,
  689. 'actual_money' => $payTotal,
  690. 'balance' => $userXd,
  691. 'create_time' => time(),
  692. 'update_time' => time(),
  693. 'remark' => "商城购物消费",
  694. 'status' => 1,
  695. 'mark' => 1,
  696. ];
  697. if(!AccountLogModel::insertGetId($log)){
  698. DB::rollBack();
  699. $this->error = 2029;
  700. RedisService::clear($cacheKey);
  701. return false;
  702. }
  703. // 更新订单状态
  704. $updateData = ['status'=>2,'pay_status'=> 1,'pay_time'=>date('Y-m-d H:i:s'),'update_time'=>time()];
  705. if(!$this->model->where(['id'=> $orderId,'mark'=>1])->update($updateData)){
  706. DB::rollBack();
  707. $this->error = 2909;
  708. RedisService::clear($cacheKey);
  709. return false;
  710. }
  711. // 待返积分奖励明细
  712. if($userAwardWaitScore>0){
  713. $log = [
  714. 'user_id' => $userId,
  715. 'source_id' => $orderId,
  716. 'source_order_no' => $orderNo,
  717. 'type' => 9,
  718. 'coin_type' => 5,
  719. 'user_type'=> 1,
  720. 'money' => $userAwardWaitScore,
  721. 'actual_money' => $userAwardWaitScore,
  722. 'balance' => $userWaitScore,
  723. 'create_time' => time(),
  724. 'update_time' => time(),
  725. 'remark' => "商城消费奖励",
  726. 'status' => 1,
  727. 'mark' => 1,
  728. ];
  729. if(!AccountLogModel::insertGetId($log)){
  730. DB::rollBack();
  731. $this->error = 2029;
  732. RedisService::clear($cacheKey);
  733. return false;
  734. }
  735. }
  736. // 算力奖励明细
  737. if($awardPowerNum>0){
  738. $log = [
  739. 'user_id' => $userId,
  740. 'source_id' => $orderId,
  741. 'source_order_no' => $orderNo,
  742. 'type' => 9,
  743. 'coin_type' => 3,
  744. 'user_type'=> 1,
  745. 'money' => $awardPowerNum,
  746. 'actual_money' => $awardPowerNum,
  747. 'balance' => $userPowerNum,
  748. 'create_time' => time(),
  749. 'update_time' => time(),
  750. 'remark' => "商城消费奖励",
  751. 'status' => 1,
  752. 'mark' => 1,
  753. ];
  754. if(!AccountLogModel::insertGetId($log)){
  755. DB::rollBack();
  756. $this->error = 2029;
  757. RedisService::clear($cacheKey);
  758. return false;
  759. }
  760. }
  761. // 推荐用户待返积分奖励明细
  762. if($inviteAwardWaitScore>0 && $parentId>0){
  763. $updateData = [
  764. 'wait_score'=>DB::raw("wait_score + {$inviteAwardWaitScore}"), // 推荐用户待返积分奖励
  765. 'update_time'=>time()
  766. ];
  767. if(!MemberModel::where(['id'=> $parentId])->update($updateData)){
  768. DB::rollBack();
  769. $this->error = 2028;
  770. RedisService::clear($cacheKey);
  771. return false;
  772. }
  773. $log = [
  774. 'user_id' => $parentId,
  775. 'source_id' => $userId,
  776. 'source_order_no' => $orderNo,
  777. 'type' => 9,
  778. 'coin_type' => 5,
  779. 'user_type'=> 1,
  780. 'money' => $userAwardWaitScore,
  781. 'actual_money' => $userAwardWaitScore,
  782. 'balance' => $userWaitScore,
  783. 'create_time' => time(),
  784. 'update_time' => time(),
  785. 'remark' => "推荐用户商城消费奖励",
  786. 'status' => 1,
  787. 'mark' => 1,
  788. ];
  789. if(!AccountLogModel::insertGetId($log)){
  790. DB::rollBack();
  791. $this->error = 2029;
  792. RedisService::clear($cacheKey);
  793. return false;
  794. }
  795. }
  796. $payStatus = 1;
  797. break;
  798. default:
  799. $this->error = 1030;
  800. return false;
  801. }
  802. // 更新优惠券状态
  803. if($couponId>0 && !MemberCouponModel::where(['id'=> $couponId,'mark'=>1])->update(['status'=> 2,'update_time'=>time()])){
  804. DB::rollBack();
  805. $this->error = 2908;
  806. RedisService::clear($cacheKey);
  807. return false;
  808. }
  809. // 购物车处理
  810. if($cartIds){
  811. CartsModel::where(['user_id'=> $userId,'status'=>1,'mark'=>1])
  812. ->whereIn('id', $cartIds)
  813. ->update(['status'=>2,'update_time'=>time()]);
  814. }
  815. // 已支付
  816. RedisService::clear($cacheKey);
  817. if($payStatus == 1){
  818. // 支付成功订单通知
  819. $message = "您在{$dateTime}(UTC+8)创建的订单【{$orderNo}】,金额{$payTotal}星豆,已支付成功。";
  820. MessageService::make()->pushMessage($userId,"订单支付成功",$message, 2);
  821. // 奖励消息
  822. // if($userAwardWaitScore>0){
  823. // $message = "您在{$dateTime}(UTC+8)成功支付{$payTotal}星豆完成购物,奖励{$userAwardWaitScore}待返积分已到账。";
  824. // MessageService::make()->pushMessage($userId,"商城消费奖励",$message, 3);
  825. // }
  826. //
  827. //
  828. // // 算力奖励消息
  829. // if($awardPowerNum>0){
  830. // $message = "您在{$dateTime}(UTC+8)成功支付{$payTotal}星豆完成购物,奖励{$awardPowerNum}算力已到账。";
  831. // MessageService::make()->pushMessage($userId,"商城消费奖励",$message, 3);
  832. // }
  833. //
  834. //
  835. // // 推荐奖励消息
  836. // if($parentId>0 && $inviteAwardWaitScore>0){
  837. // $message = "您推荐的用户【{$userId}】,在{$dateTime}(UTC+8)购物消费{$payTotal}星豆,奖励{$inviteAwardWaitScore}待返积分已到账。";
  838. // MessageService::make()->pushMessage($parentId,"推荐用户商城消费奖励",$message, 3);
  839. // }
  840. DB::commit();
  841. $this->error = 2910;
  842. return [
  843. 'id'=> $orderId,
  844. 'total'=> $payTotal,
  845. 'pay_type'=> $payType,
  846. ];
  847. }else{
  848. // 下单成功订单通知
  849. $message = "您在{$dateTime}(UTC+8)创建订单【{$orderNo}】成功,请尽快完成支付。";
  850. MessageService::make()->pushMessage($userId,"订单创建成功",$message, 2);
  851. DB::commit();
  852. $this->error = 2911;
  853. return [
  854. 'id'=> $orderId,
  855. 'total'=> $payTotal,
  856. 'pay_type'=> $payType,
  857. ];
  858. }
  859. }
  860. /**
  861. * 详情
  862. * @param $id
  863. * @return mixed
  864. */
  865. public function getInfo($id, $userId=0)
  866. {
  867. $where = [ 'a.mark' => 1];
  868. if(intval($id) == $id){
  869. $where['a.id'] = $id;
  870. }else{
  871. $where['a.order_no'] = $id;
  872. }
  873. $info = $this->model->with(['goods'])
  874. ->from('orders as a')
  875. ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
  876. ->where($where)
  877. ->select(['a.*', 'b.nickname', 'b.mobile as buy_mobile'])
  878. ->first();
  879. if ($info) {
  880. $info['create_time_text'] = $info['create_time'] ? datetime($info['create_time'], 'Y-m-d H:i:s') : '';
  881. $info['pay_time'] = $info['pay_time']? datetime($info['pay_time'], 'Y-m-d H:i:s') : '';
  882. $info['mobile'] = isset($info['mobile'])? format_mobile($info['mobile']) : '';
  883. if(isset($info['goods']) && $info['goods']){
  884. foreach ($info['goods'] as &$item){
  885. $item['main_img'] = $item['main_img']? get_image_url($item['main_img']) : '';
  886. $item['sku_attr'] = $item['sku_attr']? json_decode($item['sku_attr'],true) :[];
  887. }
  888. unset($item);
  889. }
  890. $payTypes = [10=>'星豆余额支付'];
  891. if(isset($info['pay_type'])){
  892. $info['pay_text'] = isset($payTypes[$info['pay_type']])? $payTypes[$info['pay_type']] : '其他';
  893. }
  894. $deliveryTypes = [1=>'快递配送'];
  895. if(isset($info['pay_type'])){
  896. $info['delivery_text'] = isset($deliveryTypes[$info['delivery_type']])? $deliveryTypes[$info['delivery_type']] : '其他';
  897. }
  898. }
  899. return $info;
  900. }
  901. public function pay($userId, $params)
  902. {
  903. }
  904. /**
  905. * 申请退款
  906. * @param $userId
  907. * @param $params
  908. * @return bool
  909. */
  910. public function refund($userId, $params)
  911. {
  912. $id = isset($params['id']) ? $params['id'] : 0;
  913. $goodsId = isset($params['goods_id']) ? $params['goods_id'] : 0;
  914. $refundType = isset($params['refund_type']) ? $params['refund_type'] : 0;
  915. $refundRemark = isset($params['remark']) ? $params['remark'] : '';
  916. $info = $this->model->where(['id' => $id, 'mark' => 1])
  917. ->select(['id','order_no','out_order_no','user_id','merch_id','pay_money','coupon_id','pay_status','status','refund_status','pay_time'])
  918. ->first();
  919. $status = isset($info['status']) ? $info['status'] : 0;
  920. $orderNo = isset($info['order_no']) ? $info['order_no'] : '';
  921. $outOrderNo = isset($info['out_order_no']) ? $info['out_order_no'] : '';
  922. $orderUserId = isset($info['user_id']) ? $info['user_id'] : 0;
  923. $payStatus = isset($info['pay_status']) ? $info['pay_status'] : 0;
  924. $refundStatus = isset($info['refund_status']) ? $info['refund_status'] : 0;
  925. if (!$id || empty($info)) {
  926. $this->error = 2912;
  927. return false;
  928. }
  929. // 非法操作
  930. if($userId != $orderUserId){
  931. $this->error = 2913;
  932. return false;
  933. }
  934. if(!in_array($status, [2,3])){
  935. $this->error = 2914;
  936. return false;
  937. }
  938. if($refundStatus>0){
  939. $this->error = 2915;
  940. return false;
  941. }
  942. // 订单商品
  943. /*$orderGoodsIds = OrderGoodsModel::where(['order_no'=>$orderNo,'status'=>1,'mark'=>1])->pluck('goods_id');
  944. $orderGoodsIds = $orderGoodsIds? $orderGoodsIds->toArray() : [];
  945. if(empty($orderGoodsIds) || ($goodsId && !in_array($goodsId, $orderGoodsIds))){
  946. $this->error = 2904;
  947. return false;
  948. }*/
  949. // 站外售后验证
  950. $result = SupplyService::make()->getApiData('getAfterCan',['plat_order_no'=> $outOrderNo]);
  951. $orderGoods = isset($result['order_goods'])? $result['order_goods'] : [];
  952. var_dump($orderGoods);
  953. if(empty($orderGoods)){
  954. $this->error = 2918;
  955. return false;
  956. }
  957. // 检查
  958. // foreach ($orderGoods as $item){
  959. // if($item['status'] == 0){
  960. // $this->error = 2919;
  961. // return false;
  962. // }
  963. // }
  964. //
  965. // // 站外申请售后
  966. // foreach ($orderGoods as $item){
  967. // $data = [
  968. // 'goods_sku'=> $item['goods_sku'],
  969. // 'after_type'=> $refundType,
  970. // 'after_num'=> $item['after_num'],
  971. // 'explain'=> $refundRemark,
  972. // 'order_goods_id'=> $refundRemark,
  973. // ];
  974. // $result = SupplyService::make()->getApiData('applyAfter',$data);
  975. // if($item['status'] == 0){
  976. // $this->error = 2919;
  977. // return false;
  978. // }
  979. // }
  980. //
  981. // // 处理
  982. // if(!$this->model->where(['id'=> $id,'mark'=>1])->update(['status'=> 5,'refund_status'=>1,'refund_type'=> $refundType,'refund_remark'=> $refundRemark,'refund_result'=>'','update_time'=>time()])){
  983. // $this->error = 2917;
  984. // return false;
  985. // }
  986. $this->error = 2916;
  987. return true;
  988. }
  989. /**
  990. * 申请退款取消
  991. * @param $userId
  992. * @param $params
  993. * @return bool
  994. */
  995. public function refundCancel($userId, $params)
  996. {
  997. $id = isset($params['id']) ? $params['id'] : 0;
  998. $merchId = isset($params['merch_id']) ? $params['merch_id'] : 0; // 商家
  999. $mechId = isset($params['mech_id']) ? $params['mech_id'] : 0; //技师
  1000. $info = $this->model->where(['id' => $id, 'mark' => 1])
  1001. ->select(['id','user_id','merch_id','pay_money','coupon_id','status','refund_status','refund_temp_status','pay_time'])
  1002. ->first();
  1003. $status = isset($info['status']) ? $info['status'] : 0;
  1004. $orderUserId = isset($info['user_id']) ? $info['user_id'] : 0;
  1005. $orderMerchId = isset($info['merch_id']) ? $info['merch_id'] : 0;
  1006. $orderMechId = isset($info['source_id']) ? $info['source_id'] : 0;
  1007. $refundStatus = isset($info['refund_status']) ? $info['refund_status'] : 0;
  1008. $tempStatus = isset($info['refund_temp_status']) ? $info['refund_temp_status'] : 0;
  1009. if (!$id || empty($info)) {
  1010. $this->error = 2656;
  1011. return false;
  1012. }
  1013. var_dump($info);
  1014. return false;
  1015. // 非法操作
  1016. if($merchId != $orderMerchId && $userId != $orderUserId && $mechId != $orderMechId){
  1017. $this->error = 2667;
  1018. return false;
  1019. }
  1020. if($status != 5){
  1021. $this->error = 2668;
  1022. return false;
  1023. }
  1024. if($refundStatus<=0){
  1025. $this->error = 2669;
  1026. return false;
  1027. }
  1028. // 处理
  1029. $updateData = ['status'=> $info['reception_at']? 3:2,'refund_status'=>0,'refund_remark'=> '','update_time'=>time()];
  1030. if(!$this->model->where(['id'=> $id,'mark'=>1])->update($updateData)){
  1031. $this->error = 2670;
  1032. return false;
  1033. }
  1034. $this->error = 2671;
  1035. return true;
  1036. }
  1037. /**
  1038. * 收货/已完成
  1039. * @return bool
  1040. */
  1041. public function complete($userId, $params)
  1042. {
  1043. $id = isset($params['id']) ? $params['id'] : 0;
  1044. $merchId = isset($params['merch_id']) ? $params['merch_id'] : 0;
  1045. $info = $this->model->with(['goods'])
  1046. ->where(['id' => $id, 'mark' => 1])
  1047. ->select(['id','user_id','order_no','merch_id','source_id','city','pay_money','type','postage','reception_at','coupon_id','status','is_service','refund_status','pay_time'])
  1048. ->first();
  1049. $status = isset($info['status']) ? $info['status'] : 0;
  1050. $orderUserId = isset($info['user_id']) ? $info['user_id'] : 0;
  1051. $orderMerchId = isset($info['merch_id']) ? $info['merch_id'] : 0;
  1052. $orderMechId = isset($info['source_id']) ? $info['source_id'] : 0;
  1053. $orderType = isset($info['type']) ? $info['type'] : 0;
  1054. $payMoney = isset($info['pay_money']) ? $info['pay_money'] : 0;
  1055. $goods = isset($info['goods'])? $info['goods'] : [];
  1056. if (!$id || empty($info)) {
  1057. $this->error = 2636;
  1058. return false;
  1059. }
  1060. var_dump($info);
  1061. return false;
  1062. // 非法操作
  1063. if($userId && $merchId != $orderMerchId && $orderUserId != $userId){
  1064. $this->error = 2667;
  1065. return false;
  1066. }
  1067. // 订单状态
  1068. if (($userId && $status != 3)||(!$userId && !in_array($status,[2,3]))) {
  1069. $this->error = 2668;
  1070. return false;
  1071. }
  1072. // 限制操作订单类型
  1073. if(!in_array($orderType, [1,2,6])){
  1074. $this->error = 2681;
  1075. return false;
  1076. }
  1077. // TODO 确认数据处理
  1078. DB::beginTransaction();
  1079. // 更新订单状态
  1080. if (!$this->model->where(['id' => $id])->update(['status' => 4, 'update_time' => time()])) {
  1081. DB::rollBack();
  1082. $this->error = 2678;
  1083. return false;
  1084. }
  1085. // 更新商品/服务销量
  1086. if($goods){
  1087. foreach($goods as $item){
  1088. $num = isset($item['num'])? $item['num'] : 0;
  1089. if($num>0){
  1090. GoodsModel::where(['id'=> $item['goods_id'],'mark'=>1])->update([
  1091. 'sales'=> DB::raw("sales + {$num}"),'update_time'=> time()
  1092. ]);
  1093. }
  1094. }
  1095. }
  1096. // 服务订单统计处理
  1097. if($orderType == 2){
  1098. // 更新技师服务订单,接单统计数据
  1099. $serviceCount = $this->model->where(['user_id'=> $orderUserId,'source_id'=> $orderMechId,'type'=>2,'status'=>4,'mark'=>1])->count('id');
  1100. $updateData = ['order_total'=> DB::raw("order_total + 1"),'update_time'=>time()];
  1101. if($serviceCount<=1){
  1102. $updateData['service_num'] = DB::raw("service_num + 1");
  1103. }
  1104. if($orderMechId && !MechanicModel::where(['id'=>$orderMechId,'mark'=> 1])->update($updateData)){
  1105. DB::rollBack();
  1106. $this->error = 2682;
  1107. return false;
  1108. }
  1109. // 更新商家服务订单,统计数据
  1110. $updateData = ['service_order_num'=> DB::raw("service_order_num + 1"),'service_order_total'=> DB::raw("service_order_total + {$payMoney}"),'update_time'=>time()];
  1111. if($orderMechId && !MerchantModel::where(['id'=>$orderMerchId,'mark'=> 1])->update($updateData)){
  1112. DB::rollBack();
  1113. $this->error = 2682;
  1114. return false;
  1115. }
  1116. }
  1117. // 店内订单结算
  1118. $balance = MerchantModel::where(['id'=> $orderMerchId,'mark'=>1])->value('balance');
  1119. if ($orderType == 6){
  1120. // 商家入账
  1121. $settleRate = ConfigService::make()->getConfigByCode('merch_settle_rate');
  1122. $settleRate = $settleRate>0? min(100, $settleRate) : 100;
  1123. $settleMoney = moneyFormat($payMoney * $settleRate/100, 2);
  1124. $updateData = ['balance'=> DB::raw("balance + {$settleMoney}"),'update_time'=>time()];
  1125. if($settleMoney>0 && !MerchantModel::where(['id'=> $orderMerchId,'mark'=>1])->update($updateData)){
  1126. DB::rollBack();
  1127. $this->error = 2683;
  1128. return false;
  1129. }
  1130. // 流水记录
  1131. $log = [
  1132. 'user_id'=> 0,
  1133. 'merch_id'=> $orderMerchId,
  1134. 'source_uid'=> $orderUserId,
  1135. 'source_order_no'=> isset($info['order_no'])? $info['order_no'] :'',
  1136. 'type'=> 3,
  1137. 'coin_type'=> 2,
  1138. 'user_type'=> 2,
  1139. 'money'=> $settleMoney,
  1140. 'balance'=>$balance? $balance : 0.00,
  1141. 'create_time'=> time(),
  1142. 'update_time'=> time(),
  1143. 'remark'=> '商家店内订单收入',
  1144. 'status'=>1,
  1145. 'mark'=>1
  1146. ];
  1147. if(!AccountLogModel::insertGetId($log)){
  1148. DB::rollBack();
  1149. $this->error = 2641;
  1150. return false;
  1151. }
  1152. // 平台抽成入账,财务统计
  1153. $financeMoney = floatval($payMoney - $settleMoney);
  1154. if($financeMoney>0){
  1155. $log = [
  1156. 'user_id'=> 0,
  1157. 'merch_id'=> 0,
  1158. 'source_uid'=> $orderUserId,
  1159. 'source_order_no'=> $info['order_no'],
  1160. 'type'=> 13,
  1161. 'coin_type'=> 2,
  1162. 'user_type'=> 5,
  1163. 'money'=> $financeMoney,
  1164. 'balance'=> 0,
  1165. 'create_time'=> time(),
  1166. 'update_time'=> time(),
  1167. 'remark'=> '平台店内订单收入',
  1168. 'status'=>1,
  1169. 'mark'=>1
  1170. ];
  1171. if(!AccountLogModel::insertGetId($log)){
  1172. DB::rollBack();
  1173. $this->error = 2641;
  1174. return false;
  1175. }
  1176. FinanceService::make()->saveLog(0,$financeMoney, 1, 1);
  1177. }
  1178. }
  1179. // 服务订单结算
  1180. else if(in_array($orderType, [1,2])){
  1181. // 计算服务订单分销佣金和代理佣金
  1182. if(!$result = FinanceService::make()->settleOrder($info, $userId)){
  1183. DB::rollBack();
  1184. $this->error = FinanceService::make()->getError();
  1185. return false;
  1186. }
  1187. // 商家入账
  1188. $settleMoney = isset($result['merch_money'])? $result['merch_money'] : 0;
  1189. $updateData = [
  1190. 'balance'=> DB::raw("balance + {$settleMoney}"),
  1191. 'service_order_num'=>DB::raw("service_order_num + 1"),
  1192. 'service_order_total'=>DB::raw("service_order_total + {$payMoney}"),
  1193. 'update_time'=>time()
  1194. ];
  1195. if($settleMoney>0 && !MerchantModel::where(['id'=> $orderMerchId,'mark'=>1])->update($updateData)){
  1196. DB::rollBack();
  1197. $this->error = 2683;
  1198. return false;
  1199. }
  1200. $log = [
  1201. 'user_id'=> 0,
  1202. 'merch_id'=> $orderMerchId,
  1203. 'source_uid'=> $orderUserId,
  1204. 'source_order_no'=> isset($info['order_no'])? $info['order_no'] :'',
  1205. 'type'=> 3,
  1206. 'coin_type'=> 2,
  1207. 'user_type'=> 2,
  1208. 'money'=> $settleMoney,
  1209. 'balance'=>$balance? $balance : 0.00,
  1210. 'create_time'=> time(),
  1211. 'update_time'=> time(),
  1212. 'remark'=> '商家订单收入',
  1213. 'status'=>1,
  1214. 'mark'=>1
  1215. ];
  1216. if(!AccountLogModel::insertGetId($log)){
  1217. DB::rollBack();
  1218. $this->error = 2641;
  1219. return false;
  1220. }
  1221. // 平台入账,财务统计
  1222. $financeMoney = isset($result['platform_money'])? $result['platform_money'] : 0;
  1223. if($financeMoney>0){
  1224. FinanceService::make()->saveLog(0,$financeMoney, 1, 1);
  1225. }
  1226. $log = [
  1227. 'user_id'=> 0,
  1228. 'merch_id'=> 0,
  1229. 'source_uid'=> $orderUserId,
  1230. 'source_order_no'=> isset($info['order_no'])? $info['order_no'] :'',
  1231. 'type'=> 13,
  1232. 'coin_type'=> 2,
  1233. 'user_type'=> 5,
  1234. 'money'=> $financeMoney,
  1235. 'balance'=> 0,
  1236. 'create_time'=> time(),
  1237. 'update_time'=> time(),
  1238. 'remark'=> '平台订单收入',
  1239. 'status'=>1,
  1240. 'mark'=>1
  1241. ];
  1242. if(!AccountLogModel::insertGetId($log)){
  1243. DB::rollBack();
  1244. $this->error = 2641;
  1245. return false;
  1246. }
  1247. // 技师累计
  1248. if($orderMechId){
  1249. $updateData = [
  1250. 'order_total'=> DB::raw("order_total + 1"),
  1251. 'service_num'=>DB::raw("service_num + 1"),
  1252. 'update_time'=>time()
  1253. ];
  1254. MechanicModel::where(['id'=> $orderMechId,'mark'=>1])->update($updateData);
  1255. }
  1256. }
  1257. // 消息推送
  1258. $params = [
  1259. 'title' => "订单完成通知",
  1260. 'body' => "您的订单已完成,请即时查看进度并给予评论",
  1261. 'type' => 2, // 1-公告通知,2-订单通知,3-交易通知,4-其他
  1262. 'content' => [
  1263. 'order_no' => ['name' => '订单号', 'text' => $info['order_no']],
  1264. 'time' => ['name' => '下单时间', 'text' => $info['pay_time']],
  1265. 'picker_time' => ['name' => '确认时间', 'text' => date('Y-m-d H:i:s')],
  1266. 'mechanic' => [],
  1267. 'money' => ['name' => '订单金额', 'text' => $info['pay_money']],
  1268. 'status' => ['name' => '状态', 'text' => '已完成'],
  1269. ],
  1270. 'click_type' => 'payload',
  1271. 'url' => '/pages/order/detail?id=' . $id,
  1272. ];
  1273. $mechanic = isset($info['mechanic'])? $info['mechanic'] : [];
  1274. $code = isset($mechanic['code'])? $mechanic['code'] : '';
  1275. if($code){
  1276. $params['content']['mechanic'] = ['name' => '服务技师', 'text' => "{$code}号技师"];
  1277. }
  1278. if(!PushService::make()->pushMessageByUser($info['user_id'], $params, 0)){
  1279. DB::rollBack();
  1280. $this->error = PushService::make()->getError();
  1281. return false;
  1282. }
  1283. DB::commit();
  1284. $this->error = 1002;
  1285. return true;
  1286. }
  1287. /**
  1288. * 隐藏删除
  1289. * @return false
  1290. */
  1291. public function hide($userId, $params)
  1292. {
  1293. $id = isset($params['id']) ? $params['id'] : 0;
  1294. $info = $this->model->where(['id' => $id, 'mark' => 1])
  1295. ->select(['id','user_id','order_no','status','is_hide'])
  1296. ->first();
  1297. if (!$id || empty($info)) {
  1298. $this->error = 2912;
  1299. return false;
  1300. }
  1301. $isHide = isset($info['is_hide'])? $info['is_hide'] : 0;
  1302. if($isHide >0){
  1303. $this->error = 2914;
  1304. return false;
  1305. }
  1306. if($this->model->where(['id'=> $id])->update(['is_hide'=>2,'update_time'=>time()]))
  1307. {
  1308. $this->error = 1002;
  1309. return true;
  1310. }else{
  1311. $this->error = 1003;
  1312. return false;
  1313. }
  1314. }
  1315. }