OrderService.php 74 KB

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