OrderService.php 56 KB

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