OrderService.php 56 KB

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