OrderService.php 75 KB

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