OrderService.php 55 KB

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