OrderService.php 56 KB

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