OrderService.php 74 KB

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