OrderService.php 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922
  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];
  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. foreach ($list['data'] as &$item) {
  107. $item['create_time'] = $item['create_time'] ? datetime($item['create_time'], 'Y-m-d H:i:s') : '';
  108. $item['pay_time'] = $item['pay_time'] ? datetime($item['pay_time'], 'Y-m-d H:i:s') : '';
  109. $status = isset($item['status'])? $item['status'] : 0;
  110. $item['status_text'] = '待付款';
  111. $item['refund_status_text'] = '';
  112. if($status){
  113. if($item['type'] == 2){
  114. $item['status_text'] = isset($serviceStatusArr[$status])? $serviceStatusArr[$status] : '';
  115. }else{
  116. $item['status_text'] = isset($statusArr[$status])? $statusArr[$status] : '';
  117. }
  118. }
  119. $refundStatus = isset($item['refund_status'])? $item['refund_status'] : 0;
  120. if($refundStatus && $status != 4){
  121. $item['refund_status_text'] = isset($refundStatusArr[$refundStatus])? $refundStatusArr[$refundStatus] : '';
  122. }
  123. $goods = isset($item['goods'])? $item['goods'] : [];
  124. if($goods){
  125. foreach ($goods as &$v){
  126. $v['main_img'] = isset($v['main_img']) && $v['main_img']? get_image_url($v['main_img']) : '';
  127. $v['sku_attr'] = isset($v['sku_attr']) && $v['sku_attr']? json_decode($v['sku_attr'], true) : [];
  128. }
  129. unset($v);
  130. }
  131. $item['goods'] = $goods? $goods : [];
  132. }
  133. unset($item);
  134. }
  135. return [
  136. 'pageSize' => $pageSize,
  137. 'total' => isset($list['total']) ? $list['total'] : 0,
  138. 'counts' => [],
  139. 'list' => isset($list['data']) ? $list['data'] : []
  140. ];
  141. }
  142. /**
  143. * 购买商品
  144. * @param $userId 用户ID
  145. * @param $params
  146. * @return array|false
  147. */
  148. public function buySubmit($userId, $params)
  149. {
  150. $payType = isset($params['pay_type'])? intval($params['pay_type']) : 0;
  151. $type = isset($params['type']) && $params['type']? intval($params['type']) : 1;
  152. $amount = isset($params['total']) && $params['total']? floatval($params['total']) : 0;
  153. $couponId = isset($params['coupon_id'])? intval($params['coupon_id']) : 0;
  154. $addressId = isset($params['address_id'])? intval($params['address_id']) : 0;
  155. $freightAddressId = isset($params['freight_address_id'])? intval($params['freight_address_id']) : 0;
  156. $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
  157. $skuList = isset($params['sku_list'])? $params['sku_list'] : [];
  158. $ids = isset($params['ids'])? $params['ids'] : [];
  159. $cartIds = isset($params['cart_ids'])? trim($params['cart_ids']) : '';
  160. $cartIds = $cartIds? explode('|', $cartIds) : [];
  161. if(empty($skuList) || empty($ids) || $addressId<=0 || $freightAddressId<=0 || $payType<=0){
  162. $this->error = 2420;
  163. return false;
  164. }
  165. // 锁
  166. $cacheKey = "caches:orders:buy:{$userId}";
  167. if(RedisService::get($cacheKey)){
  168. $this->error = 1053;
  169. return false;
  170. }
  171. // 订单商品
  172. $goods = GoodsService::make()->getOrderGoods($userId, $ids);
  173. if(empty($goods)){
  174. $this->error = 2903;
  175. return false;
  176. }
  177. // 格式化
  178. $skuArr = [];
  179. foreach ($skuList as $v){
  180. $skuArr[$v['goods_id']] = [
  181. 'sku_id'=> $v['sku_id'],
  182. 'num'=> $v['num'],
  183. ];
  184. }
  185. $skuList = $skuArr;
  186. $goodsNum = 0;
  187. $orderTotal = 0;
  188. $orderXdTotal = 0;
  189. $merchId = 0;
  190. $orderNo = get_order_num('XS');
  191. // 价格参数
  192. $usdtPrice = RedisService::get("caches:wallets:usdt_rate");
  193. if($usdtPrice<=0){
  194. $usdtCnyPrice = ConfigService::make()->getConfigByCode('usdt_cny_price', 7.2);
  195. $usdtPrice = $usdtCnyPrice>0 && $usdtCnyPrice< 100? $usdtCnyPrice : 0;
  196. }
  197. $xdPrice = ConfigService::make()->getConfigByCode('xd_price', 100);
  198. $xdPrice = $xdPrice > 0 && $xdPrice <= 10000 ? $xdPrice : 100;
  199. foreach($goods as &$item){
  200. $goodsId = isset($item['goods_id'])? $item['goods_id'] : 0;
  201. $merchId = isset($item['merch_id'])? $item['merch_id'] : 0;
  202. $retailPrice = isset($item['retail_price'])? $item['retail_price'] : 0;
  203. $num = isset($skuList[$goodsId]['num'])? intval($skuList[$goodsId]['num']) : 0;
  204. $skuId = isset($skuList[$goodsId]['sku_id'])? intval($skuList[$goodsId]['sku_id']) : 0;
  205. if($num>0 && $skuId >0 && $retailPrice>0){
  206. $item['price'] = moneyFormat($retailPrice/$usdtPrice * $xdPrice,2);
  207. $total = moneyFormat($retailPrice * $num, 2);
  208. $xdTotal = moneyFormat($item['price'] * $num, 2);
  209. // 订单商品
  210. $item['order_no'] = $orderNo;
  211. $item['total'] = $total;
  212. $item['xd_total'] = $xdTotal;
  213. $item['num'] = $num;
  214. $item['create_time'] = time();
  215. $item['update_time'] = time();
  216. $item['status'] = 1;
  217. $item['mark'] = 1;
  218. // 订单金额
  219. $orderTotal += $total;
  220. $orderXdTotal += $xdTotal;
  221. $goodsNum += $num;
  222. }
  223. }
  224. unset($item);
  225. if($orderXdTotal<=0 || $goodsNum<=0){
  226. $this->error = 2904;
  227. return false;
  228. }
  229. // 优惠券
  230. $couponPrice = 0;
  231. if($couponId > 0){
  232. }
  233. // 验证用户
  234. $userInfo = MemberModel::where(['id'=> $userId,'mark'=> 1,'status'=> 1])
  235. ->select(['id','nickname','pay_password','balance','parent_id','parents'])
  236. ->first();
  237. $userInfo = $userInfo? $userInfo->toArray() : [];
  238. $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
  239. $userXd = isset($userInfo['balance'])? floatval($userInfo['balance']) : 0.00;
  240. if(empty($userInfo)){
  241. $this->error = 2024;
  242. return false;
  243. }
  244. // 余额支付支付密码验证
  245. if($payType == 10 && empty($userPayPassword)){
  246. $this->error =1040;
  247. return false;
  248. }
  249. // 星豆余额支付交易密码
  250. $payPassword = get_password($payPassword);
  251. if($payType == 10 && $payPassword != $userPayPassword){
  252. $this->error = 2038;
  253. return false;
  254. }
  255. // 运费
  256. $skus = array_values($skuList);
  257. if(!$freightData = GoodsService::make()->getFreight($userId, $freightAddressId, $skus)){
  258. $this->error ='2905';
  259. return false;
  260. }
  261. $freight = isset($freightData['freight'])? floatval($freightData['freight']) : 0;
  262. $payTotal = moneyFormat($orderXdTotal+$freight,2);
  263. //var_dump($payTotal, $amount);
  264. if(intval($amount) != intval($payTotal)){
  265. $this->error ='2906';
  266. return false;
  267. }
  268. // 星豆余额支付验证
  269. if($payType == 10 && $userXd < $payTotal){
  270. $this->error = 2304;
  271. return false;
  272. }
  273. // 收货地址
  274. $addressInfo = MemberAddressService::make()->getBindInfo($userId, $addressId);
  275. $addressText = isset($addressInfo['address_text'])? $addressInfo['address_text'] : '';
  276. $city = isset($addressInfo['city'])? $addressInfo['city'] : '';
  277. $realname = isset($addressInfo['realname'])? $addressInfo['realname'] : '';
  278. $mobile = isset($addressInfo['mobile'])? $addressInfo['mobile'] : '';
  279. $address = isset($addressInfo['address'])? $addressInfo['address'] : '';
  280. if(empty($addressText) || empty($addressInfo) || empty($realname) || empty($mobile)){
  281. $this->error = 2902;
  282. return false;
  283. }
  284. $merchUId = 0;
  285. // 奖励待返积分
  286. $waitScoreRate = ConfigService::make()->getConfigByCode('shop_award_score_rate',0);
  287. $waitScoreRate = $waitScoreRate>=0 && $waitScoreRate<=1000? $waitScoreRate : 0;
  288. $awardWaitScore = moneyFormat($orderXdTotal * $waitScoreRate/100, 2);
  289. // 算力奖励
  290. $powerRate = ConfigService::make()->getConfigByCode('shop_award_power_rate',0);
  291. $powerRate = $powerRate>=0 && $powerRate<=1000? $powerRate : 0;
  292. $awardPowerNum = moneyFormat($orderXdTotal * $powerRate/100, 2);
  293. // 订单数据
  294. $order = [
  295. 'user_id'=> $userId,
  296. 'order_no'=> $orderNo,
  297. 'merch_id'=> $merchId,
  298. 'merch_uid'=> $merchUId,
  299. 'type'=> $type,
  300. 'price'=> 0.00,
  301. 'xd_price'=> $xdPrice,
  302. 'num'=> $goodsNum,
  303. 'city'=> $city,
  304. 'real_name'=> $realname,
  305. 'mobile'=> $mobile,
  306. 'address'=> $address && $addressText? $addressText.' '.$address : $addressText,
  307. 'total'=> $orderTotal,
  308. 'xd_total'=> $orderXdTotal,
  309. 'pay_type'=> $payType,
  310. 'pay_money'=> $payTotal,
  311. 'delivery_type'=> 1,
  312. 'coupon_id'=> $couponId,
  313. 'coupon_price'=> $couponPrice,
  314. 'postage'=> $freight,
  315. 'award_wait_score'=> $awardWaitScore,
  316. 'award_power_num'=> $awardPowerNum,
  317. 'create_time'=> time(),
  318. 'update_time'=> time(),
  319. 'remark'=> isset($params['remark'])? trim($params['remark']) : '',
  320. 'status'=> 1,
  321. 'mark'=> 1,
  322. ];
  323. // 站外订单提交
  324. RedisService::set($cacheKey, $order, rand(2,3));
  325. $orderParams = [
  326. 'third_order'=> $orderNo,
  327. 'address_id'=> $freightAddressId,
  328. 'sku_list'=> $skus,
  329. 'receiver'=> $realname,
  330. 'receiver_phone'=> $mobile,
  331. 'address'=> $address,
  332. 'other'=> isset($params['remark'])? $params['remark'] : '',
  333. ];
  334. $result = SupplyService::make()->getApiData('orderSubmit', $orderParams);
  335. $outOrderNo = isset($result['out_order_no'])? $result['out_order_no'] : '';
  336. $expense = isset($result['expense'])? floatval($result['expense']) : 0;
  337. $servicePrice = isset($result['service_price'])? floatval($result['service_price']) : 0;
  338. if(empty($result)){
  339. RedisService::clear($cacheKey);
  340. $this->error = SupplyService::make()->getError();
  341. return false;
  342. }
  343. // 创建订单
  344. $order['out_order_no'] = $outOrderNo;
  345. $order['expense'] = $expense;
  346. $order['service_price'] = $servicePrice;
  347. if(!$orderId = $this->model->insertGetId($order)){
  348. $this->error = 2907;
  349. RedisService::clear($cacheKey);
  350. return false;
  351. }
  352. // 写入订单商品
  353. if($orderId && !OrderGoodsModel::insert($goods)){
  354. $this->error = 2908;
  355. RedisService::clear($cacheKey);
  356. return false;
  357. }
  358. DB::beginTransaction();
  359. // 支付处理
  360. $payment = [];
  361. $dateTime = date('Y-m-d H:i:s');
  362. switch($payType){
  363. case 10: // 星豆余额支付
  364. // 扣除余额
  365. $updateData = [
  366. 'usdt'=> DB::raw("usdt - {$payTotal}"), // 扣除USDT
  367. 'update_time'=>time()
  368. ];
  369. if(!MemberModel::where(['id'=> $userId])->update($updateData)){
  370. DB::rollBack();
  371. $this->error = 1042;
  372. RedisService::clear($cacheKey);
  373. return false;
  374. }
  375. // 余额明细
  376. $log = [
  377. 'user_id' => $userId,
  378. 'source_id' => $orderId,
  379. 'source_order_no' => $orderNo,
  380. 'type' => 3,
  381. 'coin_type' => 2,
  382. 'user_type'=> 1,
  383. 'money' => $payTotal,
  384. 'actual_money' => $payTotal,
  385. 'balance' => $userXd,
  386. 'create_time' => time(),
  387. 'update_time' => time(),
  388. 'remark' => "商城购物消费",
  389. 'status' => 1,
  390. 'mark' => 1,
  391. ];
  392. if(!AccountLogModel::insertGetId($log)){
  393. DB::rollBack();
  394. $this->error = 2029;
  395. RedisService::clear($cacheKey);
  396. return false;
  397. }
  398. // 更新订单状态
  399. $updateData = ['status'=>2,'pay_status'=> 1,'pay_time'=>date('Y-m-d H:i:s'),'update_time'=>time()];
  400. if(!$this->model->where(['id'=> $orderId,'mark'=>1])->update($updateData)){
  401. DB::rollBack();
  402. $this->error = 2909;
  403. RedisService::clear($cacheKey);
  404. return false;
  405. }
  406. $payStatus = 1;
  407. break;
  408. default:
  409. $this->error = 1030;
  410. return false;
  411. }
  412. // 更新优惠券状态
  413. if($couponId>0 && !MemberCouponModel::where(['id'=> $couponId,'mark'=>1])->update(['status'=> 2,'update_time'=>time()])){
  414. DB::rollBack();
  415. $this->error = 2908;
  416. RedisService::clear($cacheKey);
  417. return false;
  418. }
  419. // 购物车处理
  420. if($cartIds){
  421. CartsModel::where(['user_id'=> $userId,'status'=>1,'mark'=>1])
  422. ->whereIn('id', $cartIds)
  423. ->update(['status'=>2,'update_time'=>time()]);
  424. }
  425. // 已支付
  426. RedisService::clear($cacheKey);
  427. if($payStatus == 1){
  428. // 支付成功订单通知
  429. $message = "您在{$dateTime}(UTC+8)创建的订单【{$orderNo}】,金额{$payTotal}星豆,已支付成功,请耐心等候发货。";
  430. MessageService::make()->pushMessage($userId,"订单支付成功",$message, 2);
  431. DB::commit();
  432. $this->error = 2910;
  433. return [
  434. 'id'=> $orderId,
  435. 'out_order_no'=> $outOrderNo,
  436. 'total'=> $payTotal,
  437. 'pay_type'=> $payType,
  438. ];
  439. }else{
  440. // 下单成功订单通知
  441. $message = "您在{$dateTime}(UTC+8)创建订单【{$orderNo}】成功,请尽快完成支付。";
  442. MessageService::make()->pushMessage($userId,"订单创建成功",$message, 2);
  443. DB::commit();
  444. $this->error = 2911;
  445. return [
  446. 'id'=> $orderId,
  447. 'out_order_no'=> $outOrderNo,
  448. 'total'=> $payTotal,
  449. 'pay_type'=> $payType,
  450. ];
  451. }
  452. }
  453. /**
  454. * 购买商品
  455. * @param $userId 用户ID
  456. * @param $params
  457. * @return array|false
  458. */
  459. public function buySubmit1($userId, $params)
  460. {
  461. $payType = isset($params['pay_type'])? intval($params['pay_type']) : 0;
  462. $type = isset($params['type']) && $params['type']? intval($params['type']) : 1;
  463. $amount = isset($params['total']) && $params['total']? floatval($params['total']) : 0;
  464. $couponId = isset($params['coupon_id'])? intval($params['coupon_id']) : 0;
  465. $addressId = isset($params['address_id'])? intval($params['address_id']) : 0;
  466. $freightAddressId = isset($params['freight_address_id'])? intval($params['freight_address_id']) : 0;
  467. $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
  468. $skuList = isset($params['sku_list'])? $params['sku_list'] : [];
  469. $ids = isset($params['ids'])? $params['ids'] : [];
  470. $cartIds = isset($params['cart_ids'])? trim($params['cart_ids']) : '';
  471. $cartIds = $cartIds? explode('|', $cartIds) : [];
  472. if(empty($skuList) || empty($ids) || $addressId<=0 || $freightAddressId<=0 || $payType<=0){
  473. $this->error = 2420;
  474. return false;
  475. }
  476. // 锁
  477. $cacheKey = "caches:orders:buy:{$userId}";
  478. if(RedisService::get($cacheKey)){
  479. $this->error = 1053;
  480. return false;
  481. }
  482. // 订单商品
  483. $goods = GoodsService::make()->getOrderGoods($userId, $ids);
  484. if(empty($goods)){
  485. $this->error = 2903;
  486. return false;
  487. }
  488. $goodsNum = 0;
  489. $orderTotal = 0;
  490. $orderXdTotal = 0;
  491. $merchId = 0;
  492. $goods = [];
  493. $orderNo = get_order_num('XS');
  494. // 价格参数
  495. $usdtPrice = RedisService::get("caches:wallets:usdt_rate");
  496. if($usdtPrice<=0){
  497. $usdtCnyPrice = ConfigService::make()->getConfigByCode('usdt_cny_price', 7.2);
  498. $usdtPrice = $usdtCnyPrice>0 && $usdtCnyPrice< 100? $usdtCnyPrice : 0;
  499. }
  500. $xdPrice = ConfigService::make()->getConfigByCode('xd_price', 100);
  501. $xdPrice = $xdPrice > 0 && $xdPrice <= 10000 ? $xdPrice : 100;
  502. foreach($goods as &$item){
  503. $goodsId = isset($item['goods_id'])? $item['goods_id'] : 0;
  504. $merchId = isset($item['merch_id'])? $item['merch_id'] : 0;
  505. $retailPrice = isset($item['retail_price'])? $item['retail_price'] : 0;
  506. $num = isset($skuList[$goodsId]['num'])? intval($skuList[$goodsId]['num']) : 0;
  507. $skuId = isset($skuList[$goodsId]['sku_id'])? intval($skuList[$goodsId]['sku_id']) : 0;
  508. if($num>0 && $skuId >0 && $retailPrice>0){
  509. $item['price'] = moneyFormat($retailPrice/$usdtPrice * $xdPrice,2);
  510. $total = moneyFormat($retailPrice * $num, 2);
  511. $xdTotal = moneyFormat($item['price'] * $num, 2);
  512. // 订单商品
  513. $item['order_no'] = $orderNo;
  514. $item['total'] = $total;
  515. $item['xd_total'] = $xdTotal;
  516. $item['num'] = $num;
  517. $item['create_time'] = time();
  518. $item['update_time'] = time();
  519. $item['status'] = 1;
  520. $item['mark'] = 1;
  521. // 订单金额
  522. $orderTotal += $total;
  523. $orderXdTotal += $xdTotal;
  524. $goodsNum += $num;
  525. }
  526. }
  527. if($orderXdTotal<=0 || $goodsNum<=0){
  528. $this->error ='2904';
  529. return false;
  530. }
  531. // 优惠券
  532. $couponPrice = 0;
  533. if($couponId > 0){
  534. }
  535. // 运费
  536. $skus = array_values($skuList);
  537. if(!$freightData = GoodsService::make()->getFreight($userId, $freightAddressId, $skus)){
  538. $this->error ='2905';
  539. return false;
  540. }
  541. $freight = isset($freightData['freight'])? floatval($freightData['freight']) : 0;
  542. $payTotal = moneyFormat($orderXdTotal+$freight,2);
  543. if($amount != $payTotal){
  544. $this->error ='2906';
  545. return false;
  546. }
  547. // 验证用户
  548. $userInfo = MemberModel::with(['parent'])->where(['id'=> $userId,'mark'=> 1,'status'=> 1])
  549. ->select(['id','nickname','pay_password','balance','usdt','power_num','wait_score','parent_id','parents'])
  550. ->first();
  551. $userInfo = $userInfo? $userInfo->toArray() : [];
  552. $parentInfo = isset($userInfo['parent'])? $userInfo['parent'] : [];
  553. $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
  554. $userXd = isset($userInfo['balance'])? floatval($userInfo['balance']) : 0.00;
  555. $userWaitScore = isset($userInfo['wait_score'])? floatval($userInfo['wait_score']) : 0.00;
  556. $userPowerNum = isset($userInfo['power_num'])? floatval($userInfo['power_num']) : 0.00;
  557. if(empty($userInfo)){
  558. $this->error = 2024;
  559. return false;
  560. }
  561. // 余额支付支付密码验证
  562. if($payType == 10 && empty($userPayPassword)){
  563. $this->error =1040;
  564. return false;
  565. }
  566. // 星豆余额支付交易密码
  567. $payPassword = get_password($payPassword);
  568. if($payType == 10 && $payPassword != $userPayPassword){
  569. $this->error = 2038;
  570. return false;
  571. }
  572. // 星豆余额支付验证
  573. if($payType == 10 && $userXd < $payTotal){
  574. $this->error = 2304;
  575. return false;
  576. }
  577. // 收货地址
  578. $addressInfo = MemberAddressService::make()->getBindInfo($userId, $addressId);
  579. $addressText = isset($addressInfo['address_text'])? $addressInfo['address_text'] : '';
  580. $city = isset($addressInfo['city'])? $addressInfo['city'] : '';
  581. $realname = isset($addressInfo['realname'])? $addressInfo['realname'] : '';
  582. $mobile = isset($addressInfo['mobile'])? $addressInfo['mobile'] : '';
  583. $address = isset($addressInfo['address'])? $addressInfo['address'] : '';
  584. if(empty($addressText) || empty($addressInfo) || empty($realname) || empty($mobile)){
  585. $this->error = 2902;
  586. return false;
  587. }
  588. $merchUId = 0;
  589. // 奖励待返积分
  590. $waitScoreRate = ConfigService::make()->getConfigByCode('shop_award_score_rate',0);
  591. $waitScoreRate = $waitScoreRate>=0 && $waitScoreRate<=1000? $waitScoreRate : 0;
  592. $awardWaitScore = moneyFormat($orderXdTotal * $waitScoreRate/100, 2);
  593. // 算力奖励
  594. $powerRate = ConfigService::make()->getConfigByCode('shop_award_power_rate',0);
  595. $powerRate = $powerRate>=0 && $powerRate<=1000? $powerRate : 0;
  596. $awardPowerNum = moneyFormat($orderXdTotal * $powerRate/100, 2);
  597. // 订单数据
  598. $order = [
  599. 'user_id'=> $userId,
  600. 'order_no'=> $orderNo,
  601. 'merch_id'=> $merchId,
  602. 'merch_uid'=> $merchUId,
  603. 'type'=> $type,
  604. 'price'=> 0.00,
  605. 'xd_price'=> $xdPrice,
  606. 'num'=> $goodsNum,
  607. 'city'=> $city,
  608. 'real_name'=> $realname,
  609. 'mobile'=> $mobile,
  610. 'address'=> $address && $addressText? $addressText.' '.$address : $addressText,
  611. 'total'=> $orderTotal,
  612. 'xd_total'=> $orderXdTotal,
  613. 'pay_type'=> $payType,
  614. 'pay_money'=> $payTotal,
  615. 'delivery_type'=> 1,
  616. 'coupon_id'=> $couponId,
  617. 'coupon_price'=> $couponPrice,
  618. 'postage'=> $freight,
  619. 'award_wait_score'=> $awardWaitScore,
  620. 'award_power_num'=> $awardPowerNum,
  621. 'create_time'=> time(),
  622. 'update_time'=> time(),
  623. 'remark'=> isset($params['remark'])? trim($params['remark']) : '',
  624. 'status'=> 1,
  625. 'mark'=> 1,
  626. ];
  627. // 创建订单
  628. DB::beginTransaction();
  629. RedisService::set($cacheKey, $order, rand(2,3));
  630. if(!$orderId = $this->model->insertGetId($order)){
  631. DB::rollBack();
  632. $this->error = 2907;
  633. RedisService::clear($cacheKey);
  634. return false;
  635. }
  636. // 写入订单商品
  637. if(!OrderGoodsModel::insert($goods)){
  638. DB::rollBack();
  639. $this->error = 2908;
  640. RedisService::clear($cacheKey);
  641. return false;
  642. }
  643. // 支付处理
  644. $payment = [];
  645. $payStatus = 2;
  646. $userAwardWaitScore = 0;
  647. $inviteAwardWaitScore = 0;
  648. $parentId = isset($parentInfo['id'])? $parentInfo['id'] : 0;
  649. $dateTime = date('Y-m-d H:i:s');
  650. switch($payType){
  651. case 10: // 星豆余额支付
  652. // 推荐用户奖励
  653. $parentStatus = isset($parentInfo['status'])? $parentInfo['status'] : 0;
  654. if($parentInfo && $parentStatus==1 && $awardWaitScore>0){
  655. // 奖励上级待返积分
  656. $inviteWaitScoreRate = ConfigService::make()->getConfigByCode('cost_award_invite_wait_score',0);
  657. $inviteWaitScoreRate = $inviteWaitScoreRate>0 && $inviteWaitScoreRate<100? $inviteWaitScoreRate : 0;
  658. $inviteAwardWaitScore = moneyFormat($awardWaitScore * $inviteWaitScoreRate/100, 2);
  659. $userAwardWaitScore = moneyFormat($awardWaitScore - $inviteAwardWaitScore, 2);
  660. }
  661. // 扣除余额
  662. $updateData = [
  663. 'usdt'=> DB::raw("usdt - {$payTotal}"), // 扣除USDT
  664. // 'wait_score'=>DB::raw("wait_score + {$userAwardWaitScore}"), // 用户待返积分奖励
  665. // 'power_num'=>DB::raw("power_num + {$awardPowerNum}"), // 算力奖励
  666. 'update_time'=>time()
  667. ];
  668. if(!MemberModel::where(['id'=> $userId])->update($updateData)){
  669. DB::rollBack();
  670. $this->error = 1042;
  671. RedisService::clear($cacheKey);
  672. return false;
  673. }
  674. // 余额明细
  675. $log = [
  676. 'user_id' => $userId,
  677. 'source_id' => $orderId,
  678. 'source_order_no' => $orderNo,
  679. 'type' => 3,
  680. 'coin_type' => 2,
  681. 'user_type'=> 1,
  682. 'money' => $payTotal,
  683. 'actual_money' => $payTotal,
  684. 'balance' => $userXd,
  685. 'create_time' => time(),
  686. 'update_time' => time(),
  687. 'remark' => "商城购物消费",
  688. 'status' => 1,
  689. 'mark' => 1,
  690. ];
  691. if(!AccountLogModel::insertGetId($log)){
  692. DB::rollBack();
  693. $this->error = 2029;
  694. RedisService::clear($cacheKey);
  695. return false;
  696. }
  697. // 更新订单状态
  698. $updateData = ['status'=>2,'pay_status'=> 1,'pay_time'=>date('Y-m-d H:i:s'),'update_time'=>time()];
  699. if(!$this->model->where(['id'=> $orderId,'mark'=>1])->update($updateData)){
  700. DB::rollBack();
  701. $this->error = 2909;
  702. RedisService::clear($cacheKey);
  703. return false;
  704. }
  705. // 待返积分奖励明细
  706. if($userAwardWaitScore>0){
  707. $log = [
  708. 'user_id' => $userId,
  709. 'source_id' => $orderId,
  710. 'source_order_no' => $orderNo,
  711. 'type' => 9,
  712. 'coin_type' => 5,
  713. 'user_type'=> 1,
  714. 'money' => $userAwardWaitScore,
  715. 'actual_money' => $userAwardWaitScore,
  716. 'balance' => $userWaitScore,
  717. 'create_time' => time(),
  718. 'update_time' => time(),
  719. 'remark' => "商城消费奖励",
  720. 'status' => 1,
  721. 'mark' => 1,
  722. ];
  723. if(!AccountLogModel::insertGetId($log)){
  724. DB::rollBack();
  725. $this->error = 2029;
  726. RedisService::clear($cacheKey);
  727. return false;
  728. }
  729. }
  730. // 算力奖励明细
  731. if($awardPowerNum>0){
  732. $log = [
  733. 'user_id' => $userId,
  734. 'source_id' => $orderId,
  735. 'source_order_no' => $orderNo,
  736. 'type' => 9,
  737. 'coin_type' => 3,
  738. 'user_type'=> 1,
  739. 'money' => $awardPowerNum,
  740. 'actual_money' => $awardPowerNum,
  741. 'balance' => $userPowerNum,
  742. 'create_time' => time(),
  743. 'update_time' => time(),
  744. 'remark' => "商城消费奖励",
  745. 'status' => 1,
  746. 'mark' => 1,
  747. ];
  748. if(!AccountLogModel::insertGetId($log)){
  749. DB::rollBack();
  750. $this->error = 2029;
  751. RedisService::clear($cacheKey);
  752. return false;
  753. }
  754. }
  755. // 推荐用户待返积分奖励明细
  756. if($inviteAwardWaitScore>0 && $parentId>0){
  757. $updateData = [
  758. 'wait_score'=>DB::raw("wait_score + {$inviteAwardWaitScore}"), // 推荐用户待返积分奖励
  759. 'update_time'=>time()
  760. ];
  761. if(!MemberModel::where(['id'=> $parentId])->update($updateData)){
  762. DB::rollBack();
  763. $this->error = 2028;
  764. RedisService::clear($cacheKey);
  765. return false;
  766. }
  767. $log = [
  768. 'user_id' => $parentId,
  769. 'source_id' => $userId,
  770. 'source_order_no' => $orderNo,
  771. 'type' => 9,
  772. 'coin_type' => 5,
  773. 'user_type'=> 1,
  774. 'money' => $userAwardWaitScore,
  775. 'actual_money' => $userAwardWaitScore,
  776. 'balance' => $userWaitScore,
  777. 'create_time' => time(),
  778. 'update_time' => time(),
  779. 'remark' => "推荐用户商城消费奖励",
  780. 'status' => 1,
  781. 'mark' => 1,
  782. ];
  783. if(!AccountLogModel::insertGetId($log)){
  784. DB::rollBack();
  785. $this->error = 2029;
  786. RedisService::clear($cacheKey);
  787. return false;
  788. }
  789. }
  790. $payStatus = 1;
  791. break;
  792. default:
  793. $this->error = 1030;
  794. return false;
  795. }
  796. // 更新优惠券状态
  797. if($couponId>0 && !MemberCouponModel::where(['id'=> $couponId,'mark'=>1])->update(['status'=> 2,'update_time'=>time()])){
  798. DB::rollBack();
  799. $this->error = 2908;
  800. RedisService::clear($cacheKey);
  801. return false;
  802. }
  803. // 购物车处理
  804. if($cartIds){
  805. CartsModel::where(['user_id'=> $userId,'status'=>1,'mark'=>1])
  806. ->whereIn('id', $cartIds)
  807. ->update(['status'=>2,'update_time'=>time()]);
  808. }
  809. // 已支付
  810. RedisService::clear($cacheKey);
  811. if($payStatus == 1){
  812. // 支付成功订单通知
  813. $message = "您在{$dateTime}(UTC+8)创建的订单【{$orderNo}】,金额{$payTotal}星豆,已支付成功。";
  814. MessageService::make()->pushMessage($userId,"订单支付成功",$message, 2);
  815. // 奖励消息
  816. // if($userAwardWaitScore>0){
  817. // $message = "您在{$dateTime}(UTC+8)成功支付{$payTotal}星豆完成购物,奖励{$userAwardWaitScore}待返积分已到账。";
  818. // MessageService::make()->pushMessage($userId,"商城消费奖励",$message, 3);
  819. // }
  820. //
  821. //
  822. // // 算力奖励消息
  823. // if($awardPowerNum>0){
  824. // $message = "您在{$dateTime}(UTC+8)成功支付{$payTotal}星豆完成购物,奖励{$awardPowerNum}算力已到账。";
  825. // MessageService::make()->pushMessage($userId,"商城消费奖励",$message, 3);
  826. // }
  827. //
  828. //
  829. // // 推荐奖励消息
  830. // if($parentId>0 && $inviteAwardWaitScore>0){
  831. // $message = "您推荐的用户【{$userId}】,在{$dateTime}(UTC+8)购物消费{$payTotal}星豆,奖励{$inviteAwardWaitScore}待返积分已到账。";
  832. // MessageService::make()->pushMessage($parentId,"推荐用户商城消费奖励",$message, 3);
  833. // }
  834. DB::commit();
  835. $this->error = 2910;
  836. return [
  837. 'id'=> $orderId,
  838. 'total'=> $payTotal,
  839. 'pay_type'=> $payType,
  840. ];
  841. }else{
  842. // 下单成功订单通知
  843. $message = "您在{$dateTime}(UTC+8)创建订单【{$orderNo}】成功,请尽快完成支付。";
  844. MessageService::make()->pushMessage($userId,"订单创建成功",$message, 2);
  845. DB::commit();
  846. $this->error = 2911;
  847. return [
  848. 'id'=> $orderId,
  849. 'total'=> $payTotal,
  850. 'pay_type'=> $payType,
  851. ];
  852. }
  853. }
  854. /**
  855. * 详情
  856. * @param $id
  857. * @return mixed
  858. */
  859. public function getInfo($id, $userId=0)
  860. {
  861. $where = [ 'a.mark' => 1];
  862. if(intval($id) == $id){
  863. $where['a.id'] = $id;
  864. }else{
  865. $where['a.order_no'] = $id;
  866. }
  867. $info = $this->model->with(['goods'])
  868. ->from('orders as a')
  869. ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
  870. ->where($where)
  871. ->select(['a.*', 'b.nickname', 'b.mobile as buy_mobile'])
  872. ->first();
  873. if ($info) {
  874. $info['create_time_text'] = $info['create_time'] ? datetime($info['create_time'], 'Y-m-d H:i:s') : '';
  875. $info['pay_time'] = $info['pay_time']? datetime($info['pay_time'], 'Y-m-d H:i:s') : '';
  876. $info['mobile'] = isset($info['mobile'])? format_mobile($info['mobile']) : '';
  877. if(isset($info['goods']) && $info['goods']){
  878. foreach ($info['goods'] as &$item){
  879. $item['main_img'] = $item['main_img']? get_image_url($item['main_img']) : '';
  880. $item['sku_attr'] = $item['sku_attr']? json_decode($item['sku_attr'],true) :[];
  881. }
  882. unset($item);
  883. }
  884. $payTypes = [10=>'星豆余额支付'];
  885. if(isset($info['pay_type'])){
  886. $info['pay_text'] = isset($payTypes[$info['pay_type']])? $payTypes[$info['pay_type']] : '其他';
  887. }
  888. $deliveryTypes = [1=>'快递配送'];
  889. if(isset($info['pay_type'])){
  890. $info['delivery_text'] = isset($deliveryTypes[$info['delivery_type']])? $deliveryTypes[$info['delivery_type']] : '其他';
  891. }
  892. }
  893. return $info;
  894. }
  895. /**
  896. * 申请退款
  897. * @param $userId
  898. * @param $params
  899. * @return bool
  900. */
  901. public function refund($userId, $params)
  902. {
  903. $id = isset($params['id']) ? $params['id'] : 0;
  904. $goodsId = isset($params['goods_id']) ? $params['goods_id'] : 0;
  905. $refundType = isset($params['refund_type']) ? $params['refund_type'] : 0;
  906. $refundRemark = isset($params['remark']) ? $params['remark'] : '';
  907. $info = $this->model->where(['id' => $id, 'mark' => 1])
  908. ->select(['id','order_no','user_id','merch_id','pay_money','coupon_id','pay_status','status','refund_status','pay_time'])
  909. ->first();
  910. $status = isset($info['status']) ? $info['status'] : 0;
  911. $orderNo = isset($info['order_no']) ? $info['order_no'] : '';
  912. $orderUserId = isset($info['user_id']) ? $info['user_id'] : 0;
  913. $payStatus = isset($info['pay_status']) ? $info['pay_status'] : 0;
  914. $refundStatus = isset($info['refund_status']) ? $info['refund_status'] : 0;
  915. if (!$id || empty($info)) {
  916. $this->error = 2912;
  917. return false;
  918. }
  919. // 非法操作
  920. if($userId != $orderUserId){
  921. $this->error = 2913;
  922. return false;
  923. }
  924. if(!in_array($status, [2,3])){
  925. $this->error = 2914;
  926. return false;
  927. }
  928. if($refundStatus>0){
  929. $this->error = 2915;
  930. return false;
  931. }
  932. // 订单商品
  933. /*$orderGoodsIds = OrderGoodsModel::where(['order_no'=>$orderNo,'status'=>1,'mark'=>1])->pluck('goods_id');
  934. $orderGoodsIds = $orderGoodsIds? $orderGoodsIds->toArray() : [];
  935. if(empty($orderGoodsIds) || ($goodsId && !in_array($goodsId, $orderGoodsIds))){
  936. $this->error = 2904;
  937. return false;
  938. }*/
  939. // 站外售后验证
  940. $result = SupplyService::make()->getApiData('getAfterCan',['plat_order_no'=> $orderNo]);
  941. $orderGoods = isset($result['order_goods'])? $result['order_goods'] : [];
  942. if(empty($orderGoods)){
  943. $this->error = 2918;
  944. return false;
  945. }
  946. // 检查
  947. foreach ($orderGoods as $item){
  948. if($item['status'] == 0){
  949. $this->error = 2919;
  950. return false;
  951. }
  952. }
  953. // 站外申请售后
  954. foreach ($orderGoods as $item){
  955. $data = [
  956. 'goods_sku'=> $item['goods_sku'],
  957. 'after_type'=> $refundType,
  958. 'after_num'=> $item['after_num'],
  959. 'explain'=> $refundRemark,
  960. 'order_goods_id'=> $refundRemark,
  961. ];
  962. $result = SupplyService::make()->getApiData('applyAfter',$data);
  963. if($item['status'] == 0){
  964. $this->error = 2919;
  965. return false;
  966. }
  967. }
  968. // 处理
  969. 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()])){
  970. $this->error = 2917;
  971. return false;
  972. }
  973. $this->error = 2916;
  974. return true;
  975. }
  976. /**
  977. * 申请退款取消
  978. * @param $userId
  979. * @param $params
  980. * @return bool
  981. */
  982. public function refundCancel($userId, $params)
  983. {
  984. $id = isset($params['id']) ? $params['id'] : 0;
  985. $merchId = isset($params['merch_id']) ? $params['merch_id'] : 0; // 商家
  986. $mechId = isset($params['mech_id']) ? $params['mech_id'] : 0; //技师
  987. $info = $this->model->where(['id' => $id, 'mark' => 1])
  988. ->select(['id','user_id','merch_id','source_id','pay_money','reception_at','coupon_id','status','refund_status','pay_time'])
  989. ->first();
  990. $status = isset($info['status']) ? $info['status'] : 0;
  991. $orderUserId = isset($info['user_id']) ? $info['user_id'] : 0;
  992. $orderMerchId = isset($info['merch_id']) ? $info['merch_id'] : 0;
  993. $orderMechId = isset($info['source_id']) ? $info['source_id'] : 0;
  994. $refundStatus = isset($info['refund_status']) ? $info['refund_status'] : 0;
  995. if (!$id || empty($info)) {
  996. $this->error = 2656;
  997. return false;
  998. }
  999. // 非法操作
  1000. if($merchId != $orderMerchId && $userId != $orderUserId && $mechId != $orderMechId){
  1001. $this->error = 2667;
  1002. return false;
  1003. }
  1004. if($status != 5){
  1005. $this->error = 2668;
  1006. return false;
  1007. }
  1008. if($refundStatus<=0){
  1009. $this->error = 2669;
  1010. return false;
  1011. }
  1012. // 处理
  1013. $updateData = ['status'=> $info['reception_at']? 3:2,'refund_status'=>0,'refund_remark'=> '','update_time'=>time()];
  1014. if(!$this->model->where(['id'=> $id,'mark'=>1])->update($updateData)){
  1015. $this->error = 2670;
  1016. return false;
  1017. }
  1018. $this->error = 2671;
  1019. return true;
  1020. }
  1021. /**
  1022. * 申请退款审核
  1023. * @param $userId
  1024. * @param $params
  1025. * @return bool
  1026. * @throws \Yansongda\Pay\Exception\ContainerException
  1027. * @throws \Yansongda\Pay\Exception\InvalidParamsException
  1028. * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
  1029. */
  1030. public function refundConfirm($userId, $params)
  1031. {
  1032. $id = isset($params['id']) ? $params['id'] : 0;
  1033. $checkStatus = isset($params['status']) ? $params['status'] : 0;
  1034. $remark = isset($params['remark']) ? $params['remark'] : '';
  1035. $merchId = isset($params['merch_id']) ? $params['merch_id'] : 0; // 商家
  1036. $info = $this->model->with(['goods'])
  1037. ->where(['id' => $id, 'mark' => 1])
  1038. ->select(['id','user_id','order_no','merch_id','source_id','type','coupon_id','pay_money','order_no','pay_type','appoint_time','reception_at','coupon_id','status','refund_status','pay_time'])
  1039. ->first();
  1040. $status = isset($info['status']) ? $info['status'] : 0;
  1041. $orderMerchId = isset($info['merch_id']) ? $info['merch_id'] : 0;
  1042. $couponId = isset($info['coupon_id']) ? $info['coupon_id'] : 0;
  1043. $orderType = isset($info['type']) ? $info['type'] : 0;
  1044. $payType = isset($info['pay_type']) ? $info['pay_type'] : 0;
  1045. $goods = isset($info['goods']) ? $info['goods'] : [];
  1046. $refundStatus = isset($info['refund_status']) ? $info['refund_status'] : 0;
  1047. $appointTime = isset($info['appoint_time']) ? $info['appoint_time'] : '';
  1048. if (!$id || empty($info)) {
  1049. $this->error = 2656;
  1050. return false;
  1051. }
  1052. // 非法操作
  1053. if($merchId != $orderMerchId){
  1054. $this->error = 2667;
  1055. return false;
  1056. }
  1057. if($status != 5){
  1058. $this->error = 2668;
  1059. return false;
  1060. }
  1061. if($refundStatus<=0){
  1062. $this->error = 2669;
  1063. return false;
  1064. }
  1065. if(!in_array($checkStatus, [2,3])){
  1066. $this->error = 2639;
  1067. return false;
  1068. }
  1069. // 支付信息
  1070. $orderNo = isset($info['order_no'])? $info['order_no'] : '';
  1071. $paymentInfo = PaymentModel::where(['order_no'=> $orderNo,'status'=>1,'mark'=>1])->first();
  1072. $totalFee = isset($paymentInfo['total_fee'])? $paymentInfo['total_fee'] : 0;
  1073. if($checkStatus == 2 && (empty($paymentInfo) || $totalFee<=0)){
  1074. $this->error = 2637;
  1075. return false;
  1076. }
  1077. $order = [
  1078. 'total_fee' => $totalFee,
  1079. 'type' => isset($info['type'])? $info['type'] : 2,
  1080. 'pay_type' => isset($info['pay_type'])? $info['pay_type'] : 0,
  1081. 'out_trade_no' => isset($paymentInfo['out_trade_no'])? $paymentInfo['out_trade_no'] : '',
  1082. 'transaction_id' => isset($paymentInfo['transaction_id'])? $paymentInfo['transaction_id'] : '',
  1083. 'order_no' => $orderNo
  1084. ];
  1085. // 退款打款请求
  1086. DB::beginTransaction();
  1087. // 审核成功,打款
  1088. $refundAmount = $totalFee;
  1089. if($checkStatus == 2){
  1090. // 超时扣费
  1091. $deductRate = ConfigService::make()->getConfigByCode('refund_deduct_rate');
  1092. $deductRate = $deductRate>0? $deductRate : 0;
  1093. // 扣除给平台
  1094. if($deductRate && $orderType == 2 && $appointTime && $appointTime<= date('m-d H:i')){
  1095. $deductMoney = moneyFormat($refundAmount * $deductRate/100, 2);
  1096. if($deductMoney>0){
  1097. // 平台入账,财务统计
  1098. $log = [
  1099. 'user_id'=> 0,
  1100. 'merch_id'=> 0,
  1101. 'source_uid'=> $info['user_id'],
  1102. 'source_order_no'=> $info['order_no'],
  1103. 'type'=> 13,
  1104. 'coin_type'=> 2,
  1105. 'user_type'=> 5,
  1106. 'money'=> $deductMoney,
  1107. 'balance'=> 0,
  1108. 'create_time'=> time(),
  1109. 'update_time'=> time(),
  1110. 'remark'=> '平台订单退款收入',
  1111. 'status'=>1,
  1112. 'mark'=>1
  1113. ];
  1114. if(!AccountLogModel::insertGetId($log)){
  1115. DB::rollBack();
  1116. $this->error = 2641;
  1117. return false;
  1118. }
  1119. FinanceService::make()->saveLog(0, $deductMoney, 1, 4);
  1120. $refundAmount = moneyFormat($refundAmount - $deductMoney, 2);
  1121. }
  1122. }
  1123. if(!PaymentService::make()->refund($order, $payType,'', $refundAmount)){
  1124. DB::rollBack();
  1125. $this->error = PaymentService::make()->getError();
  1126. return false;
  1127. }
  1128. }
  1129. // 处理
  1130. $updateData = ['status'=> 5,'refund_status'=> $checkStatus,'refund_result'=> $remark?$remark : ($checkStatus==2? '商家审核退款成功' : '退款审核失败'),'update_time'=>time()];
  1131. if(!$this->model->where(['id'=> $id,'mark'=>1])->update($updateData)){
  1132. DB::rollBack();
  1133. $this->error = 2676;
  1134. return false;
  1135. }
  1136. // 退还优惠券
  1137. if($checkStatus == 2 && $couponId){
  1138. if(!MemberCouponModel::where(['id'=> $couponId,'mark'=>1])->update(['status'=> 1,'update_time'=>time()])){
  1139. DB::rollBack();
  1140. $this->error = 2643;
  1141. return false;
  1142. }
  1143. }
  1144. // 若退款成功,商品库存返还
  1145. if($goods && $checkStatus == 2 && in_array($orderType, [1,6])){
  1146. foreach($goods as $item){
  1147. $goodsId = isset($item['goods_id'])? $item['goods_id'] : 0;
  1148. $goodsNum = isset($item['num'])? $item['num'] : 0;
  1149. if($goodsId && $goodsNum && !GoodsModel::where(['id'=> $goodsId])->increment('stock', $goodsNum)){
  1150. DB::rollBack();
  1151. $this->error = 2680;
  1152. return false;
  1153. }
  1154. }
  1155. }
  1156. $params = [
  1157. 'title' => "订单退款审核通知",
  1158. 'body' => "您申请退款的订单已经审核,请即时查看进度",
  1159. 'type' => 2, // 1-公告通知,2-订单通知,3-交易通知,4-其他
  1160. 'content' => [
  1161. 'order_no' => ['name' => '订单号', 'text' => $info['order_no']],
  1162. 'pay_time' => ['name' => '审核时间', 'text' => $info['pay_time']],
  1163. 'money' => ['name' => '订单金额', 'text' => $info['pay_money']],
  1164. 'refund_money' => ['name' => '退款金额', 'text' => $refundAmount],
  1165. 'status' => ['name' => '状态', 'text' => $checkStatus==2? '已退款':'退款失败'],
  1166. ],
  1167. 'click_type' => 'payload',
  1168. 'url' => '/pages/order/detail?id=' . $info['id'],
  1169. ];
  1170. if(!PushService::make()->pushMessageByUser($info['user_id'], $params, 0)){
  1171. DB::rollBack();
  1172. $this->error = PushService::make()->getError();
  1173. return false;
  1174. }
  1175. DB::commit();
  1176. $this->error = 2677;
  1177. return true;
  1178. }
  1179. /**
  1180. * 发货
  1181. * @return bool
  1182. */
  1183. public function delivery()
  1184. {
  1185. try {
  1186. $params = request()->all();
  1187. $id = isset($params['id']) ? $params['id'] : 0;
  1188. $merchId = isset($params['merch_id']) ? intval($params['merch_id']) : 0;
  1189. $express = isset($params['express_company']) ? $params['express_company'] : '';
  1190. $expressCode = isset($params['express_code']) ? $params['express_code'] : '';
  1191. $expressNo = isset($params['express_no']) ? $params['express_no'] : '';
  1192. $info = $this->model->where(['id' => $id, 'mark' => 1])
  1193. ->select(['id', 'user_id', 'order_no', 'merch_id', 'source_id', 'pay_money', 'reception_at', 'coupon_id', 'status', 'refund_status', 'pay_time'])
  1194. ->first();
  1195. $status = isset($info['status']) ? $info['status'] : 0;
  1196. $orderMerchId = isset($info['merch_id']) ? $info['merch_id'] : 0;
  1197. if (!$id || empty($info)) {
  1198. $this->error = 2636;
  1199. return false;
  1200. }
  1201. // if ($merchId != $orderMerchId) {
  1202. // $this->error = 2667;
  1203. // return false;
  1204. // }
  1205. if ($status != 2) {
  1206. $this->error = 2668;
  1207. return false;
  1208. }
  1209. DB::beginTransaction();
  1210. if ($this->model->where(['id' => $id])->update(['status' => 3, 'express_code' => $expressCode, 'express_company' => $express, 'express_no' => $expressNo, 'update_time' => time()])) {
  1211. $params = [
  1212. 'title' => "订单发货配送通知",
  1213. 'body' => "您的订单商家已配送,请即时查看订单进度",
  1214. 'type' => 2, // 1-公告通知,2-订单通知,3-交易通知,4-其他
  1215. 'content' => [
  1216. 'order_no' => ['name' => '订单号', 'text' => $info['order_no']],
  1217. 'time' => ['name' => '下单时间', 'text' => $info['pay_time']],
  1218. 'delivery_time' => ['name' => '配送时间', 'text' => date('Y-m-d H:i:s')],
  1219. 'money' => ['name' => '订单金额', 'text' => $info['pay_money']],
  1220. 'status' => ['name' => '状态', 'text' => '待收货'],
  1221. ],
  1222. 'click_type' => 'payload',
  1223. 'url' => '/pages/order/detail?id=' . $id,
  1224. ];
  1225. if(!PushService::make()->pushMessageByUser($info['user_id'], $params, 0)){
  1226. DB::rollBack();
  1227. $this->error = PushService::make()->getError();
  1228. return false;
  1229. }
  1230. DB::commit();
  1231. $this->error = 2673;
  1232. return true;
  1233. } else {
  1234. DB::rollBack();
  1235. $this->error = 2672;
  1236. return false;
  1237. }
  1238. } catch (\Exception $exception){
  1239. DB::rollBack();
  1240. $this->error = $exception->getMessage();
  1241. return false;
  1242. }
  1243. }
  1244. /**
  1245. * 接单
  1246. * @return bool
  1247. */
  1248. public function picker()
  1249. {
  1250. $params = request()->all();
  1251. $id = isset($params['id']) ? $params['id'] : 0;
  1252. $mechId = isset($params['mech_id']) ? intval($params['mech_id']) : 0;
  1253. $merchId = isset($params['merch_id']) ? intval($params['merch_id']) : 0;
  1254. $info = $this->model->with(['mechanic','merchant'])
  1255. ->where(['id' => $id, 'mark' => 1])
  1256. ->select(['id','user_id','order_no','merch_id','source_id','pay_money','reception_at','coupon_id','status','refund_status','pay_time','appoint_time'])
  1257. ->first();
  1258. $status = isset($info['status']) ? $info['status'] : 0;
  1259. $merchant = isset($info['merchant']) ? $info['merchant'] : [];
  1260. $merchType = isset($merchant['type']) ? $merchant['type'] : 1;
  1261. if (!$id || empty($info)) {
  1262. $this->error = 2636;
  1263. return false;
  1264. }
  1265. if ($status != 2) {
  1266. $this->error = 2668;
  1267. return false;
  1268. }
  1269. // 验证技师或个体商家是否已经存在未完成订单
  1270. $checkId = $this->model->where(['status' =>3,'mark'=>1])->where(function($query) use($mechId, $merchId, $merchType){
  1271. // 技师
  1272. if($mechId){
  1273. $query->where(['source_id'=> $mechId]);
  1274. }
  1275. // 个体商家
  1276. else if($merchId){
  1277. $query->where(['merch_id'=> $merchId]);
  1278. }
  1279. })->value('id');
  1280. if(($mechId && $checkId) || ($merchType==2 && $checkId)){
  1281. $this->error = 2698;
  1282. return false;
  1283. }
  1284. // 处理
  1285. DB::beginTransaction();
  1286. if ($this->model->where(['id' => $id])->update(['status' => 3, 'update_time' => time()])) {
  1287. $params = [
  1288. 'title' => "订单成功接单通知",
  1289. 'body' => "您的订单已被接单,请即时查看订单进度",
  1290. 'type' => 2, // 1-公告通知,2-订单通知,3-交易通知,4-其他
  1291. 'content' => [
  1292. 'order_no' => ['name' => '订单号', 'text' => $info['order_no']],
  1293. 'time' => ['name' => '下单时间', 'text' => $info['pay_time']],
  1294. 'appoint_time' => ['name' => '预约时间', 'text' => $info['appoint_time']],
  1295. 'picker_time' => ['name' => '接单时间', 'text' => date('Y-m-d H:i:s')],
  1296. 'mechanic' => [],
  1297. 'money' => ['name' => '订单金额', 'text' => $info['pay_money']],
  1298. 'status' => ['name' => '状态', 'text' => '待服务'],
  1299. ],
  1300. 'click_type' => 'payload',
  1301. 'url' => '/pages/order/detail?id=' . $id,
  1302. ];
  1303. $mechanic = isset($info['mechanic'])? $info['mechanic'] : [];
  1304. $code = isset($mechanic['code'])? $mechanic['code'] : '';
  1305. if($code){
  1306. $params['content']['mechanic'] = ['name' => '接单技师', 'text' => "{$code}号技师"];
  1307. }
  1308. if(!PushService::make()->pushMessageByUser($info['user_id'], $params, 0)){
  1309. DB::rollBack();
  1310. $this->error = PushService::make()->getError();
  1311. return false;
  1312. }
  1313. DB::commit();
  1314. $this->error = 2674;
  1315. return true;
  1316. } else {
  1317. DB::rollBack();
  1318. $this->error = 2675;
  1319. return false;
  1320. }
  1321. }
  1322. /**
  1323. * 接单/上钟
  1324. * @return bool
  1325. */
  1326. public function inService()
  1327. {
  1328. $params = request()->all();
  1329. $id = isset($params['id']) ? $params['id'] : 0;
  1330. $mechId = isset($params['mech_id']) ? intval($params['mech_id']) : 0;
  1331. $merchId = isset($params['merch_id']) ? intval($params['merch_id']) : 0;
  1332. $info = $this->model->with(['mechanic'])->where(['id' => $id, 'mark' => 1])
  1333. ->select(['id','user_id','order_no','merch_id','source_id','pay_money','reception_at','coupon_id','status','is_service','refund_status','pay_time'])
  1334. ->first();
  1335. $status = isset($info['status']) ? $info['status'] : 0;
  1336. $isService = isset($info['is_service']) ? $info['is_service'] : 0;
  1337. $orderMechId = isset($info['source_id']) ? $info['source_id'] : 0;
  1338. $orderMerchId = isset($info['merch_id']) ? $info['merch_id'] : 0;
  1339. if (!$id || empty($info)) {
  1340. $this->error = 2636;
  1341. return false;
  1342. }
  1343. // if($mechId != $orderMechId && $merchId != $orderMerchId){
  1344. // $this->error = 2667;
  1345. // return false;
  1346. // }
  1347. if ($status != 3 || $isService == 1) {
  1348. $this->error = 2668;
  1349. return false;
  1350. }
  1351. // 处理
  1352. DB::beginTransaction();
  1353. if ($this->model->where(['id' => $id])->update(['is_service' => 1, 'update_time' => time()])) {
  1354. $params = [
  1355. 'title' => "订单开始服务通知",
  1356. 'body' => "您的订单已开始服务,请即时查看进度",
  1357. 'type' => 2, // 1-公告通知,2-订单通知,3-交易通知,4-其他
  1358. 'content' => [
  1359. 'order_no' => ['name' => '订单号', 'text' => $info['order_no']],
  1360. 'time' => ['name' => '下单时间', 'text' => $info['pay_time']],
  1361. 'picker_time' => ['name' => '开始时间', 'text' => date('Y-m-d H:i:s')],
  1362. 'mechanic' => [],
  1363. 'money' => ['name' => '订单金额', 'text' => $info['pay_money']],
  1364. 'status' => ['name' => '状态', 'text' => '服务中'],
  1365. ],
  1366. 'click_type' => 'payload',
  1367. 'url' => '/pages/order/detail?id=' . $id,
  1368. ];
  1369. $mechanic = isset($info['mechanic'])? $info['mechanic'] : [];
  1370. $code = isset($mechanic['code'])? $mechanic['code'] : '';
  1371. if($code){
  1372. $params['content']['mechanic'] = ['name' => '服务技师', 'text' => "{$code}号技师"];
  1373. }
  1374. if(!PushService::make()->pushMessageByUser($info['user_id'], $params, 0)){
  1375. DB::rollBack();
  1376. $this->error = PushService::make()->getError();
  1377. return false;
  1378. }
  1379. DB::commit();
  1380. $this->error = 1003;
  1381. return true;
  1382. } else {
  1383. DB::rollBack();
  1384. $this->error = 1002;
  1385. return false;
  1386. }
  1387. }
  1388. /**
  1389. * 收货/已完成
  1390. * @return bool
  1391. */
  1392. public function complete($userId, $params)
  1393. {
  1394. $id = isset($params['id']) ? $params['id'] : 0;
  1395. $merchId = isset($params['merch_id']) ? $params['merch_id'] : 0;
  1396. $info = $this->model->with(['goods'])
  1397. ->where(['id' => $id, 'mark' => 1])
  1398. ->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'])
  1399. ->first();
  1400. $status = isset($info['status']) ? $info['status'] : 0;
  1401. $orderUserId = isset($info['user_id']) ? $info['user_id'] : 0;
  1402. $orderMerchId = isset($info['merch_id']) ? $info['merch_id'] : 0;
  1403. $orderMechId = isset($info['source_id']) ? $info['source_id'] : 0;
  1404. $orderType = isset($info['type']) ? $info['type'] : 0;
  1405. $payMoney = isset($info['pay_money']) ? $info['pay_money'] : 0;
  1406. $goods = isset($info['goods'])? $info['goods'] : [];
  1407. if (!$id || empty($info)) {
  1408. $this->error = 2636;
  1409. return false;
  1410. }
  1411. // 非法操作
  1412. if($userId && $merchId != $orderMerchId && $orderUserId != $userId){
  1413. $this->error = 2667;
  1414. return false;
  1415. }
  1416. // 订单状态
  1417. if (($userId && $status != 3)||(!$userId && !in_array($status,[2,3]))) {
  1418. $this->error = 2668;
  1419. return false;
  1420. }
  1421. // 限制操作订单类型
  1422. if(!in_array($orderType, [1,2,6])){
  1423. $this->error = 2681;
  1424. return false;
  1425. }
  1426. // TODO 确认数据处理
  1427. DB::beginTransaction();
  1428. // 更新订单状态
  1429. if (!$this->model->where(['id' => $id])->update(['status' => 4, 'update_time' => time()])) {
  1430. DB::rollBack();
  1431. $this->error = 2678;
  1432. return false;
  1433. }
  1434. // 更新商品/服务销量
  1435. if($goods){
  1436. foreach($goods as $item){
  1437. $num = isset($item['num'])? $item['num'] : 0;
  1438. if($num>0){
  1439. GoodsModel::where(['id'=> $item['goods_id'],'mark'=>1])->update([
  1440. 'sales'=> DB::raw("sales + {$num}"),'update_time'=> time()
  1441. ]);
  1442. }
  1443. }
  1444. }
  1445. // 服务订单统计处理
  1446. if($orderType == 2){
  1447. // 更新技师服务订单,接单统计数据
  1448. $serviceCount = $this->model->where(['user_id'=> $orderUserId,'source_id'=> $orderMechId,'type'=>2,'status'=>4,'mark'=>1])->count('id');
  1449. $updateData = ['order_total'=> DB::raw("order_total + 1"),'update_time'=>time()];
  1450. if($serviceCount<=1){
  1451. $updateData['service_num'] = DB::raw("service_num + 1");
  1452. }
  1453. if($orderMechId && !MechanicModel::where(['id'=>$orderMechId,'mark'=> 1])->update($updateData)){
  1454. DB::rollBack();
  1455. $this->error = 2682;
  1456. return false;
  1457. }
  1458. // 更新商家服务订单,统计数据
  1459. $updateData = ['service_order_num'=> DB::raw("service_order_num + 1"),'service_order_total'=> DB::raw("service_order_total + {$payMoney}"),'update_time'=>time()];
  1460. if($orderMechId && !MerchantModel::where(['id'=>$orderMerchId,'mark'=> 1])->update($updateData)){
  1461. DB::rollBack();
  1462. $this->error = 2682;
  1463. return false;
  1464. }
  1465. }
  1466. // 店内订单结算
  1467. $balance = MerchantModel::where(['id'=> $orderMerchId,'mark'=>1])->value('balance');
  1468. if ($orderType == 6){
  1469. // 商家入账
  1470. $settleRate = ConfigService::make()->getConfigByCode('merch_settle_rate');
  1471. $settleRate = $settleRate>0? min(100, $settleRate) : 100;
  1472. $settleMoney = moneyFormat($payMoney * $settleRate/100, 2);
  1473. $updateData = ['balance'=> DB::raw("balance + {$settleMoney}"),'update_time'=>time()];
  1474. if($settleMoney>0 && !MerchantModel::where(['id'=> $orderMerchId,'mark'=>1])->update($updateData)){
  1475. DB::rollBack();
  1476. $this->error = 2683;
  1477. return false;
  1478. }
  1479. // 流水记录
  1480. $log = [
  1481. 'user_id'=> 0,
  1482. 'merch_id'=> $orderMerchId,
  1483. 'source_uid'=> $orderUserId,
  1484. 'source_order_no'=> isset($info['order_no'])? $info['order_no'] :'',
  1485. 'type'=> 3,
  1486. 'coin_type'=> 2,
  1487. 'user_type'=> 2,
  1488. 'money'=> $settleMoney,
  1489. 'balance'=>$balance? $balance : 0.00,
  1490. 'create_time'=> time(),
  1491. 'update_time'=> time(),
  1492. 'remark'=> '商家店内订单收入',
  1493. 'status'=>1,
  1494. 'mark'=>1
  1495. ];
  1496. if(!AccountLogModel::insertGetId($log)){
  1497. DB::rollBack();
  1498. $this->error = 2641;
  1499. return false;
  1500. }
  1501. // 平台抽成入账,财务统计
  1502. $financeMoney = floatval($payMoney - $settleMoney);
  1503. if($financeMoney>0){
  1504. $log = [
  1505. 'user_id'=> 0,
  1506. 'merch_id'=> 0,
  1507. 'source_uid'=> $orderUserId,
  1508. 'source_order_no'=> $info['order_no'],
  1509. 'type'=> 13,
  1510. 'coin_type'=> 2,
  1511. 'user_type'=> 5,
  1512. 'money'=> $financeMoney,
  1513. 'balance'=> 0,
  1514. 'create_time'=> time(),
  1515. 'update_time'=> time(),
  1516. 'remark'=> '平台店内订单收入',
  1517. 'status'=>1,
  1518. 'mark'=>1
  1519. ];
  1520. if(!AccountLogModel::insertGetId($log)){
  1521. DB::rollBack();
  1522. $this->error = 2641;
  1523. return false;
  1524. }
  1525. FinanceService::make()->saveLog(0,$financeMoney, 1, 1);
  1526. }
  1527. }
  1528. // 服务订单结算
  1529. else if(in_array($orderType, [1,2])){
  1530. // 计算服务订单分销佣金和代理佣金
  1531. if(!$result = FinanceService::make()->settleOrder($info, $userId)){
  1532. DB::rollBack();
  1533. $this->error = FinanceService::make()->getError();
  1534. return false;
  1535. }
  1536. // 商家入账
  1537. $settleMoney = isset($result['merch_money'])? $result['merch_money'] : 0;
  1538. $updateData = [
  1539. 'balance'=> DB::raw("balance + {$settleMoney}"),
  1540. 'service_order_num'=>DB::raw("service_order_num + 1"),
  1541. 'service_order_total'=>DB::raw("service_order_total + {$payMoney}"),
  1542. 'update_time'=>time()
  1543. ];
  1544. if($settleMoney>0 && !MerchantModel::where(['id'=> $orderMerchId,'mark'=>1])->update($updateData)){
  1545. DB::rollBack();
  1546. $this->error = 2683;
  1547. return false;
  1548. }
  1549. $log = [
  1550. 'user_id'=> 0,
  1551. 'merch_id'=> $orderMerchId,
  1552. 'source_uid'=> $orderUserId,
  1553. 'source_order_no'=> isset($info['order_no'])? $info['order_no'] :'',
  1554. 'type'=> 3,
  1555. 'coin_type'=> 2,
  1556. 'user_type'=> 2,
  1557. 'money'=> $settleMoney,
  1558. 'balance'=>$balance? $balance : 0.00,
  1559. 'create_time'=> time(),
  1560. 'update_time'=> time(),
  1561. 'remark'=> '商家订单收入',
  1562. 'status'=>1,
  1563. 'mark'=>1
  1564. ];
  1565. if(!AccountLogModel::insertGetId($log)){
  1566. DB::rollBack();
  1567. $this->error = 2641;
  1568. return false;
  1569. }
  1570. // 平台入账,财务统计
  1571. $financeMoney = isset($result['platform_money'])? $result['platform_money'] : 0;
  1572. if($financeMoney>0){
  1573. FinanceService::make()->saveLog(0,$financeMoney, 1, 1);
  1574. }
  1575. $log = [
  1576. 'user_id'=> 0,
  1577. 'merch_id'=> 0,
  1578. 'source_uid'=> $orderUserId,
  1579. 'source_order_no'=> isset($info['order_no'])? $info['order_no'] :'',
  1580. 'type'=> 13,
  1581. 'coin_type'=> 2,
  1582. 'user_type'=> 5,
  1583. 'money'=> $financeMoney,
  1584. 'balance'=> 0,
  1585. 'create_time'=> time(),
  1586. 'update_time'=> time(),
  1587. 'remark'=> '平台订单收入',
  1588. 'status'=>1,
  1589. 'mark'=>1
  1590. ];
  1591. if(!AccountLogModel::insertGetId($log)){
  1592. DB::rollBack();
  1593. $this->error = 2641;
  1594. return false;
  1595. }
  1596. // 技师累计
  1597. if($orderMechId){
  1598. $updateData = [
  1599. 'order_total'=> DB::raw("order_total + 1"),
  1600. 'service_num'=>DB::raw("service_num + 1"),
  1601. 'update_time'=>time()
  1602. ];
  1603. MechanicModel::where(['id'=> $orderMechId,'mark'=>1])->update($updateData);
  1604. }
  1605. }
  1606. // 消息推送
  1607. $params = [
  1608. 'title' => "订单完成通知",
  1609. 'body' => "您的订单已完成,请即时查看进度并给予评论",
  1610. 'type' => 2, // 1-公告通知,2-订单通知,3-交易通知,4-其他
  1611. 'content' => [
  1612. 'order_no' => ['name' => '订单号', 'text' => $info['order_no']],
  1613. 'time' => ['name' => '下单时间', 'text' => $info['pay_time']],
  1614. 'picker_time' => ['name' => '确认时间', 'text' => date('Y-m-d H:i:s')],
  1615. 'mechanic' => [],
  1616. 'money' => ['name' => '订单金额', 'text' => $info['pay_money']],
  1617. 'status' => ['name' => '状态', 'text' => '已完成'],
  1618. ],
  1619. 'click_type' => 'payload',
  1620. 'url' => '/pages/order/detail?id=' . $id,
  1621. ];
  1622. $mechanic = isset($info['mechanic'])? $info['mechanic'] : [];
  1623. $code = isset($mechanic['code'])? $mechanic['code'] : '';
  1624. if($code){
  1625. $params['content']['mechanic'] = ['name' => '服务技师', 'text' => "{$code}号技师"];
  1626. }
  1627. if(!PushService::make()->pushMessageByUser($info['user_id'], $params, 0)){
  1628. DB::rollBack();
  1629. $this->error = PushService::make()->getError();
  1630. return false;
  1631. }
  1632. DB::commit();
  1633. $this->error = 1002;
  1634. return true;
  1635. }
  1636. /**
  1637. * 评论
  1638. * @return bool
  1639. */
  1640. public function comment($userId, $params)
  1641. {
  1642. $orderId = isset($params['order_id']) ? $params['order_id'] : 0;
  1643. $info = $this->model->where(['id' => $orderId, 'mark' => 1])->first();
  1644. $status = isset($info['status']) ? $info['status'] : 0;
  1645. if (!$orderId || empty($info)) {
  1646. $this->error = 2689;
  1647. return false;
  1648. }
  1649. if (!in_array($status, [3, 4])) {
  1650. $this->error = 2668;
  1651. return false;
  1652. }
  1653. $score = isset($params['score'])? intval($params['score']) : 0;
  1654. $score = $score>0 && $score<=5? $score : 0;
  1655. if($score<=0){
  1656. $this->error = 2691;
  1657. return false;
  1658. }
  1659. // 是否已经评论
  1660. $comment = MerchantCommentModel::where(['user_id'=> $userId,'order_id'=> $orderId,'mark'=>1])
  1661. ->select(['id','status'])
  1662. ->first();
  1663. $status = isset($comment['status'])? $comment['status'] : 0;
  1664. $commentId = isset($comment['id'])? $comment['id'] : 0;
  1665. if($comment && $status == 1){
  1666. $this->error = 2690;
  1667. return false;
  1668. }
  1669. $content = isset($params['content'])? $params['content'] : '';
  1670. $content = $content? MessageService::make()->filterMessage($content) : '';
  1671. $albums = isset($params['albums'])? get_format_images($params['albums']) : '';
  1672. $merchId = isset($info['merch_id'])? $info['merch_id'] : 0;
  1673. $publishTime = ConfigService::make()->getConfigByCode('publish_auto_check_time');
  1674. $publishTime = $publishTime? $publishTime : 0;
  1675. $publishAt = date('Y-m-d H:i:s', time() + $publishTime * 60);
  1676. $orderGoodsId = OrderGoodsModel::where(['order_no'=> $info['order_no'],'status'=>1,'mark'=>1])->pluck('goods_id');
  1677. $orderGoodsId = $orderGoodsId? $orderGoodsId->toArray() : [];
  1678. $data = [
  1679. 'user_id'=> $userId,
  1680. 'order_id'=> $orderId,
  1681. 'merch_id'=> $merchId,
  1682. 'mech_id'=> isset($info['source_id'])? $info['source_id'] : 0,
  1683. 'reply_id'=> isset($params['reply_id'])? $params['reply_id'] : 0,
  1684. 'content'=> $content,
  1685. 'albums'=> $albums,
  1686. 'score'=> $score,
  1687. 'goods'=> $orderGoodsId? implode(',', $orderGoodsId) : '',
  1688. 'update_time'=> time(),
  1689. 'publish_time'=> $publishAt,
  1690. 'status'=> 1,
  1691. ];
  1692. DB::beginTransaction();
  1693. if($comment){
  1694. if(!MerchantCommentModel::where(['id'=> $commentId])->update($data)){
  1695. DB::rollBack();
  1696. $this->error = 2693;
  1697. return false;
  1698. }
  1699. }else{
  1700. $data['create_time'] = time();
  1701. if(!$commentId = MerchantCommentModel::insertGetId($data)){
  1702. DB::rollBack();
  1703. $this->error = 2693;
  1704. return false;
  1705. }
  1706. }
  1707. $updateData = ['score_rate'=> DB::raw("(score_rate+{$score})/2"),'update_time'=>time()];
  1708. if(!MerchantModel::where(['id'=> $merchId])->update($updateData)){
  1709. DB::rollBack();
  1710. $this->error = 2693;
  1711. return false;
  1712. }
  1713. DB::commit();
  1714. $this->error = lang('2692',['time'=> $publishTime? $publishTime:'0']);
  1715. return ['id'=> $commentId];
  1716. }
  1717. /**
  1718. * 隐藏订单
  1719. * @return false
  1720. */
  1721. public function hide()
  1722. {
  1723. $params = request()->all();
  1724. $id = isset($params['id']) ? $params['id'] : 0;
  1725. $info = $this->model->where(['id' => $id, 'mark' => 1])
  1726. ->select(['id','user_id','order_no','merch_id','source_id','status','user_delete'])
  1727. ->first();
  1728. if (!$id || empty($info)) {
  1729. $this->error = 2636;
  1730. return false;
  1731. }
  1732. $userDelete = isset($info['user_delete'])? $info['user_delete'] : 0;
  1733. if($userDelete == 2){
  1734. $this->error = 2235;
  1735. return false;
  1736. }
  1737. if($this->model->where(['id'=> $id])->update(['user_delete'=>2,'update_time'=>time()]))
  1738. {
  1739. $this->error = 2236;
  1740. return true;
  1741. }else{
  1742. $this->error = 2237;
  1743. return false;
  1744. }
  1745. }
  1746. }