OrderService.php 56 KB

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