OrderService.php 56 KB

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