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