OrderService.php 56 KB

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