OrderService.php 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917
  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];
  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. foreach ($list['data'] as &$item) {
  107. $item['create_time'] = $item['create_time'] ? datetime($item['create_time'], 'Y-m-d H:i:s') : '';
  108. $item['pay_time'] = $item['pay_time'] ? datetime($item['pay_time'], 'Y-m-d H:i:s') : '';
  109. $status = isset($item['status'])? $item['status'] : 0;
  110. $item['status_text'] = '待付款';
  111. $item['refund_status_text'] = '';
  112. if($status){
  113. if($item['type'] == 2){
  114. $item['status_text'] = isset($serviceStatusArr[$status])? $serviceStatusArr[$status] : '';
  115. }else{
  116. $item['status_text'] = isset($statusArr[$status])? $statusArr[$status] : '';
  117. }
  118. }
  119. $refundStatus = isset($item['refund_status'])? $item['refund_status'] : 0;
  120. if($refundStatus && $status != 4){
  121. $item['refund_status_text'] = isset($refundStatusArr[$refundStatus])? $refundStatusArr[$refundStatus] : '';
  122. }
  123. $goods = isset($item['goods'])? $item['goods'] : [];
  124. if($goods){
  125. foreach ($goods as &$v){
  126. $v['main_img'] = isset($v['main_img']) && $v['main_img']? get_image_url($v['main_img']) : '';
  127. $v['sku_attr'] = isset($v['sku_attr']) && $v['sku_attr']? json_decode($v['sku_attr'], true) : [];
  128. }
  129. unset($v);
  130. }
  131. $item['goods'] = $goods? $goods : [];
  132. }
  133. unset($item);
  134. }
  135. return [
  136. 'pageSize' => $pageSize,
  137. 'total' => isset($list['total']) ? $list['total'] : 0,
  138. 'counts' => [],
  139. 'list' => isset($list['data']) ? $list['data'] : []
  140. ];
  141. }
  142. /**
  143. * 购买商品
  144. * @param $userId 用户ID
  145. * @param $params
  146. * @return array|false
  147. */
  148. public function buySubmit($userId, $params)
  149. {
  150. $payType = isset($params['pay_type'])? intval($params['pay_type']) : 0;
  151. $type = isset($params['type']) && $params['type']? intval($params['type']) : 1;
  152. $amount = isset($params['total']) && $params['total']? floatval($params['total']) : 0;
  153. $couponId = isset($params['coupon_id'])? intval($params['coupon_id']) : 0;
  154. $addressId = isset($params['address_id'])? intval($params['address_id']) : 0;
  155. $freightAddressId = isset($params['freight_address_id'])? intval($params['freight_address_id']) : 0;
  156. $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
  157. $skuList = isset($params['sku_list'])? $params['sku_list'] : [];
  158. $ids = isset($params['ids'])? $params['ids'] : [];
  159. $cartIds = isset($params['cart_ids'])? trim($params['cart_ids']) : '';
  160. $cartIds = $cartIds? explode('|', $cartIds) : [];
  161. if(empty($skuList) || empty($ids) || $addressId<=0 || $freightAddressId<=0 || $payType<=0){
  162. $this->error = 2420;
  163. return false;
  164. }
  165. // 锁
  166. $cacheKey = "caches:orders:buy:{$userId}";
  167. if(RedisService::get($cacheKey)){
  168. $this->error = 1053;
  169. return false;
  170. }
  171. $time = microtime(true);
  172. // 订单商品
  173. $goods = GoodsService::make()->getOrderGoods($userId, $ids);
  174. if(empty($goods)){
  175. $this->error = 2903;
  176. return false;
  177. }
  178. $end = microtime(true);
  179. var_dump($end - $time);
  180. $goodsNum = 0;
  181. $orderTotal = 0;
  182. $orderXdTotal = 0;
  183. $merchId = 0;
  184. $orderNo = get_order_num('XS');
  185. // 价格参数
  186. $usdtPrice = RedisService::get("caches:wallets:usdt_rate");
  187. if($usdtPrice<=0){
  188. $usdtCnyPrice = ConfigService::make()->getConfigByCode('usdt_cny_price', 7.2);
  189. $usdtPrice = $usdtCnyPrice>0 && $usdtCnyPrice< 100? $usdtCnyPrice : 0;
  190. }
  191. $xdPrice = ConfigService::make()->getConfigByCode('xd_price', 100);
  192. $xdPrice = $xdPrice > 0 && $xdPrice <= 10000 ? $xdPrice : 100;
  193. foreach($goods as &$item){
  194. $goodsId = isset($item['goods_id'])? $item['goods_id'] : 0;
  195. $merchId = isset($item['merch_id'])? $item['merch_id'] : 0;
  196. $retailPrice = isset($item['retail_price'])? $item['retail_price'] : 0;
  197. $num = isset($skuList[$goodsId]['num'])? intval($skuList[$goodsId]['num']) : 0;
  198. $skuId = isset($skuList[$goodsId]['sku_id'])? intval($skuList[$goodsId]['sku_id']) : 0;
  199. if($num>0 && $skuId >0 && $retailPrice>0){
  200. $item['price'] = moneyFormat($retailPrice/$usdtPrice * $xdPrice,2);
  201. $total = moneyFormat($retailPrice * $num, 2);
  202. $xdTotal = moneyFormat($item['price'] * $num, 2);
  203. // 订单商品
  204. $item['order_no'] = $orderNo;
  205. $item['total'] = $total;
  206. $item['xd_total'] = $xdTotal;
  207. $item['num'] = $num;
  208. $item['create_time'] = time();
  209. $item['update_time'] = time();
  210. $item['status'] = 1;
  211. $item['mark'] = 1;
  212. // 订单金额
  213. $orderTotal += $total;
  214. $orderXdTotal += $xdTotal;
  215. $goodsNum += $num;
  216. }
  217. }
  218. unset($item);
  219. if($orderXdTotal<=0 || $goodsNum<=0){
  220. $this->error = 2904;
  221. return false;
  222. }
  223. // 优惠券
  224. $couponPrice = 0;
  225. if($couponId > 0){
  226. }
  227. $end = microtime(true);
  228. var_dump($end - $time);
  229. // 验证用户
  230. $userInfo = MemberModel::where(['id'=> $userId,'mark'=> 1,'status'=> 1])
  231. ->select(['id','nickname','pay_password','balance','parent_id','parents'])
  232. ->first();
  233. $userInfo = $userInfo? $userInfo->toArray() : [];
  234. $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
  235. $userXd = isset($userInfo['balance'])? floatval($userInfo['balance']) : 0.00;
  236. if(empty($userInfo)){
  237. $this->error = 2024;
  238. return false;
  239. }
  240. // 余额支付支付密码验证
  241. if($payType == 10 && empty($userPayPassword)){
  242. $this->error =1040;
  243. return false;
  244. }
  245. $end = microtime(true);
  246. var_dump($end - $time);
  247. // 星豆余额支付交易密码
  248. $payPassword = get_password($payPassword);
  249. if($payType == 10 && $payPassword != $userPayPassword){
  250. $this->error = 2038;
  251. return false;
  252. }
  253. // 运费
  254. $skus = array_values($skuList);
  255. if(!$freightData = GoodsService::make()->getFreight($userId, $freightAddressId, $skus)){
  256. $this->error ='2905';
  257. return false;
  258. }
  259. $freight = isset($freightData['freight'])? floatval($freightData['freight']) : 0;
  260. $payTotal = moneyFormat($orderXdTotal+$freight,2);
  261. //var_dump($payTotal, $amount);
  262. if(intval($amount) != intval($payTotal)){
  263. $this->error ='2906';
  264. return false;
  265. }
  266. // 星豆余额支付验证
  267. if($payType == 10 && $userXd < $payTotal){
  268. $this->error = 2304;
  269. return false;
  270. }
  271. // 收货地址
  272. $addressInfo = MemberAddressService::make()->getBindInfo($userId, $addressId);
  273. $addressText = isset($addressInfo['address_text'])? $addressInfo['address_text'] : '';
  274. $city = isset($addressInfo['city'])? $addressInfo['city'] : '';
  275. $realname = isset($addressInfo['realname'])? $addressInfo['realname'] : '';
  276. $mobile = isset($addressInfo['mobile'])? $addressInfo['mobile'] : '';
  277. $address = isset($addressInfo['address'])? $addressInfo['address'] : '';
  278. if(empty($addressText) || empty($addressInfo) || empty($realname) || empty($mobile)){
  279. $this->error = 2902;
  280. return false;
  281. }
  282. $merchUId = 0;
  283. // 奖励待返积分
  284. $waitScoreRate = ConfigService::make()->getConfigByCode('shop_award_score_rate',0);
  285. $waitScoreRate = $waitScoreRate>=0 && $waitScoreRate<=1000? $waitScoreRate : 0;
  286. $awardWaitScore = moneyFormat($orderXdTotal * $waitScoreRate/100, 2);
  287. // 算力奖励
  288. $powerRate = ConfigService::make()->getConfigByCode('shop_award_power_rate',0);
  289. $powerRate = $powerRate>=0 && $powerRate<=1000? $powerRate : 0;
  290. $awardPowerNum = moneyFormat($orderXdTotal * $powerRate/100, 2);
  291. // 订单数据
  292. $order = [
  293. 'user_id'=> $userId,
  294. 'order_no'=> $orderNo,
  295. 'merch_id'=> $merchId,
  296. 'merch_uid'=> $merchUId,
  297. 'type'=> $type,
  298. 'price'=> 0.00,
  299. 'xd_price'=> $xdPrice,
  300. 'num'=> $goodsNum,
  301. 'city'=> $city,
  302. 'real_name'=> $realname,
  303. 'mobile'=> $mobile,
  304. 'address'=> $address && $addressText? $addressText.' '.$address : $addressText,
  305. 'total'=> $orderTotal,
  306. 'xd_total'=> $orderXdTotal,
  307. 'pay_type'=> $payType,
  308. 'pay_money'=> $payTotal,
  309. 'delivery_type'=> 1,
  310. 'coupon_id'=> $couponId,
  311. 'coupon_price'=> $couponPrice,
  312. 'postage'=> $freight,
  313. 'award_wait_score'=> $awardWaitScore,
  314. 'award_power_num'=> $awardPowerNum,
  315. 'create_time'=> time(),
  316. 'update_time'=> time(),
  317. 'remark'=> isset($params['remark'])? trim($params['remark']) : '',
  318. 'status'=> 1,
  319. 'mark'=> 1,
  320. ];
  321. // 站外订单提交
  322. RedisService::set($cacheKey, $order, rand(2,3));
  323. $orderParams = [
  324. 'third_order'=> $orderNo,
  325. 'address_id'=> $freightAddressId,
  326. 'sku_list'=> $skus,
  327. 'receiver'=> $realname,
  328. 'receiver_phone'=> $mobile,
  329. 'address'=> $address,
  330. 'other'=> isset($params['remark'])? $params['remark'] : '',
  331. ];
  332. $result = SupplyService::make()->getApiData('orderSubmit', $orderParams);
  333. $outOrderNo = isset($result['out_order_no'])? $result['out_order_no'] : '';
  334. $expense = isset($result['expense'])? floatval($result['expense']) : 0;
  335. $servicePrice = isset($result['service_price'])? floatval($result['service_price']) : 0;
  336. if(empty($result)){
  337. RedisService::clear($cacheKey);
  338. $this->error = SupplyService::make()->getError();
  339. return false;
  340. }
  341. // 创建订单
  342. $order['out_order_no'] = $outOrderNo;
  343. $order['expense'] = $expense;
  344. $order['service_price'] = $servicePrice;
  345. if(!$orderId = $this->model->insertGetId($order)){
  346. $this->error = 2907;
  347. RedisService::clear($cacheKey);
  348. return false;
  349. }
  350. // 写入订单商品
  351. if($orderId && !OrderGoodsModel::insert($goods)){
  352. $this->error = 2908;
  353. RedisService::clear($cacheKey);
  354. return false;
  355. }
  356. DB::beginTransaction();
  357. // 支付处理
  358. $payment = [];
  359. $dateTime = date('Y-m-d H:i:s');
  360. switch($payType){
  361. case 10: // 星豆余额支付
  362. // 扣除余额
  363. $updateData = [
  364. 'usdt'=> DB::raw("usdt - {$payTotal}"), // 扣除USDT
  365. 'update_time'=>time()
  366. ];
  367. if(!MemberModel::where(['id'=> $userId])->update($updateData)){
  368. DB::rollBack();
  369. $this->error = 1042;
  370. RedisService::clear($cacheKey);
  371. return false;
  372. }
  373. // 余额明细
  374. $log = [
  375. 'user_id' => $userId,
  376. 'source_id' => $orderId,
  377. 'source_order_no' => $orderNo,
  378. 'type' => 3,
  379. 'coin_type' => 2,
  380. 'user_type'=> 1,
  381. 'money' => $payTotal,
  382. 'actual_money' => $payTotal,
  383. 'balance' => $userXd,
  384. 'create_time' => time(),
  385. 'update_time' => time(),
  386. 'remark' => "商城购物消费",
  387. 'status' => 1,
  388. 'mark' => 1,
  389. ];
  390. if(!AccountLogModel::insertGetId($log)){
  391. DB::rollBack();
  392. $this->error = 2029;
  393. RedisService::clear($cacheKey);
  394. return false;
  395. }
  396. // 更新订单状态
  397. $updateData = ['status'=>2,'pay_status'=> 1,'pay_time'=>date('Y-m-d H:i:s'),'update_time'=>time()];
  398. if(!$this->model->where(['id'=> $orderId,'mark'=>1])->update($updateData)){
  399. DB::rollBack();
  400. $this->error = 2909;
  401. RedisService::clear($cacheKey);
  402. return false;
  403. }
  404. $payStatus = 1;
  405. break;
  406. default:
  407. $this->error = 1030;
  408. return false;
  409. }
  410. // 更新优惠券状态
  411. if($couponId>0 && !MemberCouponModel::where(['id'=> $couponId,'mark'=>1])->update(['status'=> 2,'update_time'=>time()])){
  412. DB::rollBack();
  413. $this->error = 2908;
  414. RedisService::clear($cacheKey);
  415. return false;
  416. }
  417. // 购物车处理
  418. if($cartIds){
  419. CartsModel::where(['user_id'=> $userId,'status'=>1,'mark'=>1])
  420. ->whereIn('id', $cartIds)
  421. ->update(['status'=>2,'update_time'=>time()]);
  422. }
  423. // 已支付
  424. RedisService::clear($cacheKey);
  425. if($payStatus == 1){
  426. // 支付成功订单通知
  427. $message = "您在{$dateTime}(UTC+8)创建的订单【{$orderNo}】,金额{$payTotal}星豆,已支付成功,请耐心等候发货。";
  428. MessageService::make()->pushMessage($userId,"订单支付成功",$message, 2);
  429. DB::commit();
  430. $this->error = 2910;
  431. return [
  432. 'id'=> $orderId,
  433. 'out_order_no'=> $outOrderNo,
  434. 'total'=> $payTotal,
  435. 'pay_type'=> $payType,
  436. ];
  437. }else{
  438. // 下单成功订单通知
  439. $message = "您在{$dateTime}(UTC+8)创建订单【{$orderNo}】成功,请尽快完成支付。";
  440. MessageService::make()->pushMessage($userId,"订单创建成功",$message, 2);
  441. DB::commit();
  442. $this->error = 2911;
  443. return [
  444. 'id'=> $orderId,
  445. 'out_order_no'=> $outOrderNo,
  446. 'total'=> $payTotal,
  447. 'pay_type'=> $payType,
  448. ];
  449. }
  450. }
  451. /**
  452. * 购买商品
  453. * @param $userId 用户ID
  454. * @param $params
  455. * @return array|false
  456. */
  457. public function buySubmit1($userId, $params)
  458. {
  459. $payType = isset($params['pay_type'])? intval($params['pay_type']) : 0;
  460. $type = isset($params['type']) && $params['type']? intval($params['type']) : 1;
  461. $amount = isset($params['total']) && $params['total']? floatval($params['total']) : 0;
  462. $couponId = isset($params['coupon_id'])? intval($params['coupon_id']) : 0;
  463. $addressId = isset($params['address_id'])? intval($params['address_id']) : 0;
  464. $freightAddressId = isset($params['freight_address_id'])? intval($params['freight_address_id']) : 0;
  465. $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
  466. $skuList = isset($params['sku_list'])? $params['sku_list'] : [];
  467. $ids = isset($params['ids'])? $params['ids'] : [];
  468. $cartIds = isset($params['cart_ids'])? trim($params['cart_ids']) : '';
  469. $cartIds = $cartIds? explode('|', $cartIds) : [];
  470. if(empty($skuList) || empty($ids) || $addressId<=0 || $freightAddressId<=0 || $payType<=0){
  471. $this->error = 2420;
  472. return false;
  473. }
  474. // 锁
  475. $cacheKey = "caches:orders:buy:{$userId}";
  476. if(RedisService::get($cacheKey)){
  477. $this->error = 1053;
  478. return false;
  479. }
  480. // 订单商品
  481. $goods = GoodsService::make()->getOrderGoods($userId, $ids);
  482. if(empty($goods)){
  483. $this->error = 2903;
  484. return false;
  485. }
  486. $goodsNum = 0;
  487. $orderTotal = 0;
  488. $orderXdTotal = 0;
  489. $merchId = 0;
  490. $goods = [];
  491. $orderNo = get_order_num('XS');
  492. // 价格参数
  493. $usdtPrice = RedisService::get("caches:wallets:usdt_rate");
  494. if($usdtPrice<=0){
  495. $usdtCnyPrice = ConfigService::make()->getConfigByCode('usdt_cny_price', 7.2);
  496. $usdtPrice = $usdtCnyPrice>0 && $usdtCnyPrice< 100? $usdtCnyPrice : 0;
  497. }
  498. $xdPrice = ConfigService::make()->getConfigByCode('xd_price', 100);
  499. $xdPrice = $xdPrice > 0 && $xdPrice <= 10000 ? $xdPrice : 100;
  500. foreach($goods as &$item){
  501. $goodsId = isset($item['goods_id'])? $item['goods_id'] : 0;
  502. $merchId = isset($item['merch_id'])? $item['merch_id'] : 0;
  503. $retailPrice = isset($item['retail_price'])? $item['retail_price'] : 0;
  504. $num = isset($skuList[$goodsId]['num'])? intval($skuList[$goodsId]['num']) : 0;
  505. $skuId = isset($skuList[$goodsId]['sku_id'])? intval($skuList[$goodsId]['sku_id']) : 0;
  506. if($num>0 && $skuId >0 && $retailPrice>0){
  507. $item['price'] = moneyFormat($retailPrice/$usdtPrice * $xdPrice,2);
  508. $total = moneyFormat($retailPrice * $num, 2);
  509. $xdTotal = moneyFormat($item['price'] * $num, 2);
  510. // 订单商品
  511. $item['order_no'] = $orderNo;
  512. $item['total'] = $total;
  513. $item['xd_total'] = $xdTotal;
  514. $item['num'] = $num;
  515. $item['create_time'] = time();
  516. $item['update_time'] = time();
  517. $item['status'] = 1;
  518. $item['mark'] = 1;
  519. // 订单金额
  520. $orderTotal += $total;
  521. $orderXdTotal += $xdTotal;
  522. $goodsNum += $num;
  523. }
  524. }
  525. if($orderXdTotal<=0 || $goodsNum<=0){
  526. $this->error ='2904';
  527. return false;
  528. }
  529. // 优惠券
  530. $couponPrice = 0;
  531. if($couponId > 0){
  532. }
  533. // 运费
  534. $skus = array_values($skuList);
  535. if(!$freightData = GoodsService::make()->getFreight($userId, $freightAddressId, $skus)){
  536. $this->error ='2905';
  537. return false;
  538. }
  539. $freight = isset($freightData['freight'])? floatval($freightData['freight']) : 0;
  540. $payTotal = moneyFormat($orderXdTotal+$freight,2);
  541. if($amount != $payTotal){
  542. $this->error ='2906';
  543. return false;
  544. }
  545. // 验证用户
  546. $userInfo = MemberModel::with(['parent'])->where(['id'=> $userId,'mark'=> 1,'status'=> 1])
  547. ->select(['id','nickname','pay_password','balance','usdt','power_num','wait_score','parent_id','parents'])
  548. ->first();
  549. $userInfo = $userInfo? $userInfo->toArray() : [];
  550. $parentInfo = isset($userInfo['parent'])? $userInfo['parent'] : [];
  551. $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
  552. $userXd = isset($userInfo['balance'])? floatval($userInfo['balance']) : 0.00;
  553. $userWaitScore = isset($userInfo['wait_score'])? floatval($userInfo['wait_score']) : 0.00;
  554. $userPowerNum = isset($userInfo['power_num'])? floatval($userInfo['power_num']) : 0.00;
  555. if(empty($userInfo)){
  556. $this->error = 2024;
  557. return false;
  558. }
  559. // 余额支付支付密码验证
  560. if($payType == 10 && empty($userPayPassword)){
  561. $this->error =1040;
  562. return false;
  563. }
  564. // 星豆余额支付交易密码
  565. $payPassword = get_password($payPassword);
  566. if($payType == 10 && $payPassword != $userPayPassword){
  567. $this->error = 2038;
  568. return false;
  569. }
  570. // 星豆余额支付验证
  571. if($payType == 10 && $userXd < $payTotal){
  572. $this->error = 2304;
  573. return false;
  574. }
  575. // 收货地址
  576. $addressInfo = MemberAddressService::make()->getBindInfo($userId, $addressId);
  577. $addressText = isset($addressInfo['address_text'])? $addressInfo['address_text'] : '';
  578. $city = isset($addressInfo['city'])? $addressInfo['city'] : '';
  579. $realname = isset($addressInfo['realname'])? $addressInfo['realname'] : '';
  580. $mobile = isset($addressInfo['mobile'])? $addressInfo['mobile'] : '';
  581. $address = isset($addressInfo['address'])? $addressInfo['address'] : '';
  582. if(empty($addressText) || empty($addressInfo) || empty($realname) || empty($mobile)){
  583. $this->error = 2902;
  584. return false;
  585. }
  586. $merchUId = 0;
  587. // 奖励待返积分
  588. $waitScoreRate = ConfigService::make()->getConfigByCode('shop_award_score_rate',0);
  589. $waitScoreRate = $waitScoreRate>=0 && $waitScoreRate<=1000? $waitScoreRate : 0;
  590. $awardWaitScore = moneyFormat($orderXdTotal * $waitScoreRate/100, 2);
  591. // 算力奖励
  592. $powerRate = ConfigService::make()->getConfigByCode('shop_award_power_rate',0);
  593. $powerRate = $powerRate>=0 && $powerRate<=1000? $powerRate : 0;
  594. $awardPowerNum = moneyFormat($orderXdTotal * $powerRate/100, 2);
  595. // 订单数据
  596. $order = [
  597. 'user_id'=> $userId,
  598. 'order_no'=> $orderNo,
  599. 'merch_id'=> $merchId,
  600. 'merch_uid'=> $merchUId,
  601. 'type'=> $type,
  602. 'price'=> 0.00,
  603. 'xd_price'=> $xdPrice,
  604. 'num'=> $goodsNum,
  605. 'city'=> $city,
  606. 'real_name'=> $realname,
  607. 'mobile'=> $mobile,
  608. 'address'=> $address && $addressText? $addressText.' '.$address : $addressText,
  609. 'total'=> $orderTotal,
  610. 'xd_total'=> $orderXdTotal,
  611. 'pay_type'=> $payType,
  612. 'pay_money'=> $payTotal,
  613. 'delivery_type'=> 1,
  614. 'coupon_id'=> $couponId,
  615. 'coupon_price'=> $couponPrice,
  616. 'postage'=> $freight,
  617. 'award_wait_score'=> $awardWaitScore,
  618. 'award_power_num'=> $awardPowerNum,
  619. 'create_time'=> time(),
  620. 'update_time'=> time(),
  621. 'remark'=> isset($params['remark'])? trim($params['remark']) : '',
  622. 'status'=> 1,
  623. 'mark'=> 1,
  624. ];
  625. // 创建订单
  626. DB::beginTransaction();
  627. RedisService::set($cacheKey, $order, rand(2,3));
  628. if(!$orderId = $this->model->insertGetId($order)){
  629. DB::rollBack();
  630. $this->error = 2907;
  631. RedisService::clear($cacheKey);
  632. return false;
  633. }
  634. // 写入订单商品
  635. if(!OrderGoodsModel::insert($goods)){
  636. DB::rollBack();
  637. $this->error = 2908;
  638. RedisService::clear($cacheKey);
  639. return false;
  640. }
  641. // 支付处理
  642. $payment = [];
  643. $payStatus = 2;
  644. $userAwardWaitScore = 0;
  645. $inviteAwardWaitScore = 0;
  646. $parentId = isset($parentInfo['id'])? $parentInfo['id'] : 0;
  647. $dateTime = date('Y-m-d H:i:s');
  648. switch($payType){
  649. case 10: // 星豆余额支付
  650. // 推荐用户奖励
  651. $parentStatus = isset($parentInfo['status'])? $parentInfo['status'] : 0;
  652. if($parentInfo && $parentStatus==1 && $awardWaitScore>0){
  653. // 奖励上级待返积分
  654. $inviteWaitScoreRate = ConfigService::make()->getConfigByCode('cost_award_invite_wait_score',0);
  655. $inviteWaitScoreRate = $inviteWaitScoreRate>0 && $inviteWaitScoreRate<100? $inviteWaitScoreRate : 0;
  656. $inviteAwardWaitScore = moneyFormat($awardWaitScore * $inviteWaitScoreRate/100, 2);
  657. $userAwardWaitScore = moneyFormat($awardWaitScore - $inviteAwardWaitScore, 2);
  658. }
  659. // 扣除余额
  660. $updateData = [
  661. 'usdt'=> DB::raw("usdt - {$payTotal}"), // 扣除USDT
  662. // 'wait_score'=>DB::raw("wait_score + {$userAwardWaitScore}"), // 用户待返积分奖励
  663. // 'power_num'=>DB::raw("power_num + {$awardPowerNum}"), // 算力奖励
  664. 'update_time'=>time()
  665. ];
  666. if(!MemberModel::where(['id'=> $userId])->update($updateData)){
  667. DB::rollBack();
  668. $this->error = 1042;
  669. RedisService::clear($cacheKey);
  670. return false;
  671. }
  672. // 余额明细
  673. $log = [
  674. 'user_id' => $userId,
  675. 'source_id' => $orderId,
  676. 'source_order_no' => $orderNo,
  677. 'type' => 3,
  678. 'coin_type' => 2,
  679. 'user_type'=> 1,
  680. 'money' => $payTotal,
  681. 'actual_money' => $payTotal,
  682. 'balance' => $userXd,
  683. 'create_time' => time(),
  684. 'update_time' => time(),
  685. 'remark' => "商城购物消费",
  686. 'status' => 1,
  687. 'mark' => 1,
  688. ];
  689. if(!AccountLogModel::insertGetId($log)){
  690. DB::rollBack();
  691. $this->error = 2029;
  692. RedisService::clear($cacheKey);
  693. return false;
  694. }
  695. // 更新订单状态
  696. $updateData = ['status'=>2,'pay_status'=> 1,'pay_time'=>date('Y-m-d H:i:s'),'update_time'=>time()];
  697. if(!$this->model->where(['id'=> $orderId,'mark'=>1])->update($updateData)){
  698. DB::rollBack();
  699. $this->error = 2909;
  700. RedisService::clear($cacheKey);
  701. return false;
  702. }
  703. // 待返积分奖励明细
  704. if($userAwardWaitScore>0){
  705. $log = [
  706. 'user_id' => $userId,
  707. 'source_id' => $orderId,
  708. 'source_order_no' => $orderNo,
  709. 'type' => 9,
  710. 'coin_type' => 5,
  711. 'user_type'=> 1,
  712. 'money' => $userAwardWaitScore,
  713. 'actual_money' => $userAwardWaitScore,
  714. 'balance' => $userWaitScore,
  715. 'create_time' => time(),
  716. 'update_time' => time(),
  717. 'remark' => "商城消费奖励",
  718. 'status' => 1,
  719. 'mark' => 1,
  720. ];
  721. if(!AccountLogModel::insertGetId($log)){
  722. DB::rollBack();
  723. $this->error = 2029;
  724. RedisService::clear($cacheKey);
  725. return false;
  726. }
  727. }
  728. // 算力奖励明细
  729. if($awardPowerNum>0){
  730. $log = [
  731. 'user_id' => $userId,
  732. 'source_id' => $orderId,
  733. 'source_order_no' => $orderNo,
  734. 'type' => 9,
  735. 'coin_type' => 3,
  736. 'user_type'=> 1,
  737. 'money' => $awardPowerNum,
  738. 'actual_money' => $awardPowerNum,
  739. 'balance' => $userPowerNum,
  740. 'create_time' => time(),
  741. 'update_time' => time(),
  742. 'remark' => "商城消费奖励",
  743. 'status' => 1,
  744. 'mark' => 1,
  745. ];
  746. if(!AccountLogModel::insertGetId($log)){
  747. DB::rollBack();
  748. $this->error = 2029;
  749. RedisService::clear($cacheKey);
  750. return false;
  751. }
  752. }
  753. // 推荐用户待返积分奖励明细
  754. if($inviteAwardWaitScore>0 && $parentId>0){
  755. $updateData = [
  756. 'wait_score'=>DB::raw("wait_score + {$inviteAwardWaitScore}"), // 推荐用户待返积分奖励
  757. 'update_time'=>time()
  758. ];
  759. if(!MemberModel::where(['id'=> $parentId])->update($updateData)){
  760. DB::rollBack();
  761. $this->error = 2028;
  762. RedisService::clear($cacheKey);
  763. return false;
  764. }
  765. $log = [
  766. 'user_id' => $parentId,
  767. 'source_id' => $userId,
  768. 'source_order_no' => $orderNo,
  769. 'type' => 9,
  770. 'coin_type' => 5,
  771. 'user_type'=> 1,
  772. 'money' => $userAwardWaitScore,
  773. 'actual_money' => $userAwardWaitScore,
  774. 'balance' => $userWaitScore,
  775. 'create_time' => time(),
  776. 'update_time' => time(),
  777. 'remark' => "推荐用户商城消费奖励",
  778. 'status' => 1,
  779. 'mark' => 1,
  780. ];
  781. if(!AccountLogModel::insertGetId($log)){
  782. DB::rollBack();
  783. $this->error = 2029;
  784. RedisService::clear($cacheKey);
  785. return false;
  786. }
  787. }
  788. $payStatus = 1;
  789. break;
  790. default:
  791. $this->error = 1030;
  792. return false;
  793. }
  794. // 更新优惠券状态
  795. if($couponId>0 && !MemberCouponModel::where(['id'=> $couponId,'mark'=>1])->update(['status'=> 2,'update_time'=>time()])){
  796. DB::rollBack();
  797. $this->error = 2908;
  798. RedisService::clear($cacheKey);
  799. return false;
  800. }
  801. // 购物车处理
  802. if($cartIds){
  803. CartsModel::where(['user_id'=> $userId,'status'=>1,'mark'=>1])
  804. ->whereIn('id', $cartIds)
  805. ->update(['status'=>2,'update_time'=>time()]);
  806. }
  807. // 已支付
  808. RedisService::clear($cacheKey);
  809. if($payStatus == 1){
  810. // 支付成功订单通知
  811. $message = "您在{$dateTime}(UTC+8)创建的订单【{$orderNo}】,金额{$payTotal}星豆,已支付成功。";
  812. MessageService::make()->pushMessage($userId,"订单支付成功",$message, 2);
  813. // 奖励消息
  814. // if($userAwardWaitScore>0){
  815. // $message = "您在{$dateTime}(UTC+8)成功支付{$payTotal}星豆完成购物,奖励{$userAwardWaitScore}待返积分已到账。";
  816. // MessageService::make()->pushMessage($userId,"商城消费奖励",$message, 3);
  817. // }
  818. //
  819. //
  820. // // 算力奖励消息
  821. // if($awardPowerNum>0){
  822. // $message = "您在{$dateTime}(UTC+8)成功支付{$payTotal}星豆完成购物,奖励{$awardPowerNum}算力已到账。";
  823. // MessageService::make()->pushMessage($userId,"商城消费奖励",$message, 3);
  824. // }
  825. //
  826. //
  827. // // 推荐奖励消息
  828. // if($parentId>0 && $inviteAwardWaitScore>0){
  829. // $message = "您推荐的用户【{$userId}】,在{$dateTime}(UTC+8)购物消费{$payTotal}星豆,奖励{$inviteAwardWaitScore}待返积分已到账。";
  830. // MessageService::make()->pushMessage($parentId,"推荐用户商城消费奖励",$message, 3);
  831. // }
  832. DB::commit();
  833. $this->error = 2910;
  834. return [
  835. 'id'=> $orderId,
  836. 'total'=> $payTotal,
  837. 'pay_type'=> $payType,
  838. ];
  839. }else{
  840. // 下单成功订单通知
  841. $message = "您在{$dateTime}(UTC+8)创建订单【{$orderNo}】成功,请尽快完成支付。";
  842. MessageService::make()->pushMessage($userId,"订单创建成功",$message, 2);
  843. DB::commit();
  844. $this->error = 2911;
  845. return [
  846. 'id'=> $orderId,
  847. 'total'=> $payTotal,
  848. 'pay_type'=> $payType,
  849. ];
  850. }
  851. }
  852. /**
  853. * 详情
  854. * @param $id
  855. * @return mixed
  856. */
  857. public function getInfo($id, $userId=0)
  858. {
  859. $where = [ 'a.mark' => 1];
  860. if(intval($id) == $id){
  861. $where['a.id'] = $id;
  862. }else{
  863. $where['a.order_no'] = $id;
  864. }
  865. $info = $this->model->with(['goods'])
  866. ->from('orders as a')
  867. ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
  868. ->where($where)
  869. ->select(['a.*', 'b.nickname', 'b.mobile as buy_mobile'])
  870. ->first();
  871. if ($info) {
  872. $info['create_time_text'] = $info['create_time'] ? datetime($info['create_time'], 'Y-m-d H:i:s') : '';
  873. $info['pay_time'] = $info['pay_time']? datetime($info['pay_time'], 'Y-m-d H:i:s') : '';
  874. $info['mobile'] = isset($info['mobile'])? format_mobile($info['mobile']) : '';
  875. if(isset($info['goods']) && $info['goods']){
  876. foreach ($info['goods'] as &$item){
  877. $item['main_img'] = $item['main_img']? get_image_url($item['main_img']) : '';
  878. $item['sku_attr'] = $item['sku_attr']? json_decode($item['sku_attr'],true) :[];
  879. }
  880. unset($item);
  881. }
  882. $payTypes = [10=>'星豆余额支付'];
  883. if(isset($info['pay_type'])){
  884. $info['pay_text'] = isset($payTypes[$info['pay_type']])? $payTypes[$info['pay_type']] : '其他';
  885. }
  886. $deliveryTypes = [1=>'快递配送'];
  887. if(isset($info['pay_type'])){
  888. $info['delivery_text'] = isset($deliveryTypes[$info['delivery_type']])? $deliveryTypes[$info['delivery_type']] : '其他';
  889. }
  890. }
  891. return $info;
  892. }
  893. /**
  894. * 申请退款
  895. * @param $userId
  896. * @param $params
  897. * @return bool
  898. */
  899. public function refund($userId, $params)
  900. {
  901. $id = isset($params['id']) ? $params['id'] : 0;
  902. $goodsId = isset($params['goods_id']) ? $params['goods_id'] : 0;
  903. $refundType = isset($params['refund_type']) ? $params['refund_type'] : 0;
  904. $refundRemark = isset($params['remark']) ? $params['remark'] : '';
  905. $info = $this->model->where(['id' => $id, 'mark' => 1])
  906. ->select(['id','order_no','user_id','merch_id','pay_money','coupon_id','pay_status','status','refund_status','pay_time'])
  907. ->first();
  908. $status = isset($info['status']) ? $info['status'] : 0;
  909. $orderNo = isset($info['order_no']) ? $info['order_no'] : '';
  910. $orderUserId = isset($info['user_id']) ? $info['user_id'] : 0;
  911. $payStatus = isset($info['pay_status']) ? $info['pay_status'] : 0;
  912. $refundStatus = isset($info['refund_status']) ? $info['refund_status'] : 0;
  913. if (!$id || empty($info)) {
  914. $this->error = 2912;
  915. return false;
  916. }
  917. // 非法操作
  918. if($userId != $orderUserId){
  919. $this->error = 2913;
  920. return false;
  921. }
  922. if(!in_array($status, [2,3])){
  923. $this->error = 2914;
  924. return false;
  925. }
  926. if($refundStatus>0){
  927. $this->error = 2915;
  928. return false;
  929. }
  930. // 订单商品
  931. /*$orderGoodsIds = OrderGoodsModel::where(['order_no'=>$orderNo,'status'=>1,'mark'=>1])->pluck('goods_id');
  932. $orderGoodsIds = $orderGoodsIds? $orderGoodsIds->toArray() : [];
  933. if(empty($orderGoodsIds) || ($goodsId && !in_array($goodsId, $orderGoodsIds))){
  934. $this->error = 2904;
  935. return false;
  936. }*/
  937. // 站外售后验证
  938. $result = SupplyService::make()->getApiData('getAfterCan',['plat_order_no'=> $orderNo]);
  939. $orderGoods = isset($result['order_goods'])? $result['order_goods'] : [];
  940. if(empty($orderGoods)){
  941. $this->error = 2918;
  942. return false;
  943. }
  944. // 检查
  945. foreach ($orderGoods as $item){
  946. if($item['status'] == 0){
  947. $this->error = 2919;
  948. return false;
  949. }
  950. }
  951. // 站外申请售后
  952. foreach ($orderGoods as $item){
  953. $data = [
  954. 'goods_sku'=> $item['goods_sku'],
  955. 'after_type'=> $refundType,
  956. 'after_num'=> $item['after_num'],
  957. 'explain'=> $refundRemark,
  958. 'order_goods_id'=> $refundRemark,
  959. ];
  960. $result = SupplyService::make()->getApiData('applyAfter',$data);
  961. if($item['status'] == 0){
  962. $this->error = 2919;
  963. return false;
  964. }
  965. }
  966. // 处理
  967. 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()])){
  968. $this->error = 2917;
  969. return false;
  970. }
  971. $this->error = 2916;
  972. return true;
  973. }
  974. /**
  975. * 申请退款取消
  976. * @param $userId
  977. * @param $params
  978. * @return bool
  979. */
  980. public function refundCancel($userId, $params)
  981. {
  982. $id = isset($params['id']) ? $params['id'] : 0;
  983. $merchId = isset($params['merch_id']) ? $params['merch_id'] : 0; // 商家
  984. $mechId = isset($params['mech_id']) ? $params['mech_id'] : 0; //技师
  985. $info = $this->model->where(['id' => $id, 'mark' => 1])
  986. ->select(['id','user_id','merch_id','source_id','pay_money','reception_at','coupon_id','status','refund_status','pay_time'])
  987. ->first();
  988. $status = isset($info['status']) ? $info['status'] : 0;
  989. $orderUserId = isset($info['user_id']) ? $info['user_id'] : 0;
  990. $orderMerchId = isset($info['merch_id']) ? $info['merch_id'] : 0;
  991. $orderMechId = isset($info['source_id']) ? $info['source_id'] : 0;
  992. $refundStatus = isset($info['refund_status']) ? $info['refund_status'] : 0;
  993. if (!$id || empty($info)) {
  994. $this->error = 2656;
  995. return false;
  996. }
  997. // 非法操作
  998. if($merchId != $orderMerchId && $userId != $orderUserId && $mechId != $orderMechId){
  999. $this->error = 2667;
  1000. return false;
  1001. }
  1002. if($status != 5){
  1003. $this->error = 2668;
  1004. return false;
  1005. }
  1006. if($refundStatus<=0){
  1007. $this->error = 2669;
  1008. return false;
  1009. }
  1010. // 处理
  1011. $updateData = ['status'=> $info['reception_at']? 3:2,'refund_status'=>0,'refund_remark'=> '','update_time'=>time()];
  1012. if(!$this->model->where(['id'=> $id,'mark'=>1])->update($updateData)){
  1013. $this->error = 2670;
  1014. return false;
  1015. }
  1016. $this->error = 2671;
  1017. return true;
  1018. }
  1019. /**
  1020. * 申请退款审核
  1021. * @param $userId
  1022. * @param $params
  1023. * @return bool
  1024. * @throws \Yansongda\Pay\Exception\ContainerException
  1025. * @throws \Yansongda\Pay\Exception\InvalidParamsException
  1026. * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
  1027. */
  1028. public function refundConfirm($userId, $params)
  1029. {
  1030. $id = isset($params['id']) ? $params['id'] : 0;
  1031. $checkStatus = isset($params['status']) ? $params['status'] : 0;
  1032. $remark = isset($params['remark']) ? $params['remark'] : '';
  1033. $merchId = isset($params['merch_id']) ? $params['merch_id'] : 0; // 商家
  1034. $info = $this->model->with(['goods'])
  1035. ->where(['id' => $id, 'mark' => 1])
  1036. ->select(['id','user_id','order_no','merch_id','source_id','type','coupon_id','pay_money','order_no','pay_type','appoint_time','reception_at','coupon_id','status','refund_status','pay_time'])
  1037. ->first();
  1038. $status = isset($info['status']) ? $info['status'] : 0;
  1039. $orderMerchId = isset($info['merch_id']) ? $info['merch_id'] : 0;
  1040. $couponId = isset($info['coupon_id']) ? $info['coupon_id'] : 0;
  1041. $orderType = isset($info['type']) ? $info['type'] : 0;
  1042. $payType = isset($info['pay_type']) ? $info['pay_type'] : 0;
  1043. $goods = isset($info['goods']) ? $info['goods'] : [];
  1044. $refundStatus = isset($info['refund_status']) ? $info['refund_status'] : 0;
  1045. $appointTime = isset($info['appoint_time']) ? $info['appoint_time'] : '';
  1046. if (!$id || empty($info)) {
  1047. $this->error = 2656;
  1048. return false;
  1049. }
  1050. // 非法操作
  1051. if($merchId != $orderMerchId){
  1052. $this->error = 2667;
  1053. return false;
  1054. }
  1055. if($status != 5){
  1056. $this->error = 2668;
  1057. return false;
  1058. }
  1059. if($refundStatus<=0){
  1060. $this->error = 2669;
  1061. return false;
  1062. }
  1063. if(!in_array($checkStatus, [2,3])){
  1064. $this->error = 2639;
  1065. return false;
  1066. }
  1067. // 支付信息
  1068. $orderNo = isset($info['order_no'])? $info['order_no'] : '';
  1069. $paymentInfo = PaymentModel::where(['order_no'=> $orderNo,'status'=>1,'mark'=>1])->first();
  1070. $totalFee = isset($paymentInfo['total_fee'])? $paymentInfo['total_fee'] : 0;
  1071. if($checkStatus == 2 && (empty($paymentInfo) || $totalFee<=0)){
  1072. $this->error = 2637;
  1073. return false;
  1074. }
  1075. $order = [
  1076. 'total_fee' => $totalFee,
  1077. 'type' => isset($info['type'])? $info['type'] : 2,
  1078. 'pay_type' => isset($info['pay_type'])? $info['pay_type'] : 0,
  1079. 'out_trade_no' => isset($paymentInfo['out_trade_no'])? $paymentInfo['out_trade_no'] : '',
  1080. 'transaction_id' => isset($paymentInfo['transaction_id'])? $paymentInfo['transaction_id'] : '',
  1081. 'order_no' => $orderNo
  1082. ];
  1083. // 退款打款请求
  1084. DB::beginTransaction();
  1085. // 审核成功,打款
  1086. $refundAmount = $totalFee;
  1087. if($checkStatus == 2){
  1088. // 超时扣费
  1089. $deductRate = ConfigService::make()->getConfigByCode('refund_deduct_rate');
  1090. $deductRate = $deductRate>0? $deductRate : 0;
  1091. // 扣除给平台
  1092. if($deductRate && $orderType == 2 && $appointTime && $appointTime<= date('m-d H:i')){
  1093. $deductMoney = moneyFormat($refundAmount * $deductRate/100, 2);
  1094. if($deductMoney>0){
  1095. // 平台入账,财务统计
  1096. $log = [
  1097. 'user_id'=> 0,
  1098. 'merch_id'=> 0,
  1099. 'source_uid'=> $info['user_id'],
  1100. 'source_order_no'=> $info['order_no'],
  1101. 'type'=> 13,
  1102. 'coin_type'=> 2,
  1103. 'user_type'=> 5,
  1104. 'money'=> $deductMoney,
  1105. 'balance'=> 0,
  1106. 'create_time'=> time(),
  1107. 'update_time'=> time(),
  1108. 'remark'=> '平台订单退款收入',
  1109. 'status'=>1,
  1110. 'mark'=>1
  1111. ];
  1112. if(!AccountLogModel::insertGetId($log)){
  1113. DB::rollBack();
  1114. $this->error = 2641;
  1115. return false;
  1116. }
  1117. FinanceService::make()->saveLog(0, $deductMoney, 1, 4);
  1118. $refundAmount = moneyFormat($refundAmount - $deductMoney, 2);
  1119. }
  1120. }
  1121. if(!PaymentService::make()->refund($order, $payType,'', $refundAmount)){
  1122. DB::rollBack();
  1123. $this->error = PaymentService::make()->getError();
  1124. return false;
  1125. }
  1126. }
  1127. // 处理
  1128. $updateData = ['status'=> 5,'refund_status'=> $checkStatus,'refund_result'=> $remark?$remark : ($checkStatus==2? '商家审核退款成功' : '退款审核失败'),'update_time'=>time()];
  1129. if(!$this->model->where(['id'=> $id,'mark'=>1])->update($updateData)){
  1130. DB::rollBack();
  1131. $this->error = 2676;
  1132. return false;
  1133. }
  1134. // 退还优惠券
  1135. if($checkStatus == 2 && $couponId){
  1136. if(!MemberCouponModel::where(['id'=> $couponId,'mark'=>1])->update(['status'=> 1,'update_time'=>time()])){
  1137. DB::rollBack();
  1138. $this->error = 2643;
  1139. return false;
  1140. }
  1141. }
  1142. // 若退款成功,商品库存返还
  1143. if($goods && $checkStatus == 2 && in_array($orderType, [1,6])){
  1144. foreach($goods as $item){
  1145. $goodsId = isset($item['goods_id'])? $item['goods_id'] : 0;
  1146. $goodsNum = isset($item['num'])? $item['num'] : 0;
  1147. if($goodsId && $goodsNum && !GoodsModel::where(['id'=> $goodsId])->increment('stock', $goodsNum)){
  1148. DB::rollBack();
  1149. $this->error = 2680;
  1150. return false;
  1151. }
  1152. }
  1153. }
  1154. $params = [
  1155. 'title' => "订单退款审核通知",
  1156. 'body' => "您申请退款的订单已经审核,请即时查看进度",
  1157. 'type' => 2, // 1-公告通知,2-订单通知,3-交易通知,4-其他
  1158. 'content' => [
  1159. 'order_no' => ['name' => '订单号', 'text' => $info['order_no']],
  1160. 'pay_time' => ['name' => '审核时间', 'text' => $info['pay_time']],
  1161. 'money' => ['name' => '订单金额', 'text' => $info['pay_money']],
  1162. 'refund_money' => ['name' => '退款金额', 'text' => $refundAmount],
  1163. 'status' => ['name' => '状态', 'text' => $checkStatus==2? '已退款':'退款失败'],
  1164. ],
  1165. 'click_type' => 'payload',
  1166. 'url' => '/pages/order/detail?id=' . $info['id'],
  1167. ];
  1168. if(!PushService::make()->pushMessageByUser($info['user_id'], $params, 0)){
  1169. DB::rollBack();
  1170. $this->error = PushService::make()->getError();
  1171. return false;
  1172. }
  1173. DB::commit();
  1174. $this->error = 2677;
  1175. return true;
  1176. }
  1177. /**
  1178. * 发货
  1179. * @return bool
  1180. */
  1181. public function delivery()
  1182. {
  1183. try {
  1184. $params = request()->all();
  1185. $id = isset($params['id']) ? $params['id'] : 0;
  1186. $merchId = isset($params['merch_id']) ? intval($params['merch_id']) : 0;
  1187. $express = isset($params['express_company']) ? $params['express_company'] : '';
  1188. $expressCode = isset($params['express_code']) ? $params['express_code'] : '';
  1189. $expressNo = isset($params['express_no']) ? $params['express_no'] : '';
  1190. $info = $this->model->where(['id' => $id, 'mark' => 1])
  1191. ->select(['id', 'user_id', 'order_no', 'merch_id', 'source_id', 'pay_money', 'reception_at', 'coupon_id', 'status', 'refund_status', 'pay_time'])
  1192. ->first();
  1193. $status = isset($info['status']) ? $info['status'] : 0;
  1194. $orderMerchId = isset($info['merch_id']) ? $info['merch_id'] : 0;
  1195. if (!$id || empty($info)) {
  1196. $this->error = 2636;
  1197. return false;
  1198. }
  1199. // if ($merchId != $orderMerchId) {
  1200. // $this->error = 2667;
  1201. // return false;
  1202. // }
  1203. if ($status != 2) {
  1204. $this->error = 2668;
  1205. return false;
  1206. }
  1207. DB::beginTransaction();
  1208. if ($this->model->where(['id' => $id])->update(['status' => 3, 'express_code' => $expressCode, 'express_company' => $express, 'express_no' => $expressNo, 'update_time' => time()])) {
  1209. $params = [
  1210. 'title' => "订单发货配送通知",
  1211. 'body' => "您的订单商家已配送,请即时查看订单进度",
  1212. 'type' => 2, // 1-公告通知,2-订单通知,3-交易通知,4-其他
  1213. 'content' => [
  1214. 'order_no' => ['name' => '订单号', 'text' => $info['order_no']],
  1215. 'time' => ['name' => '下单时间', 'text' => $info['pay_time']],
  1216. 'delivery_time' => ['name' => '配送时间', 'text' => date('Y-m-d H:i:s')],
  1217. 'money' => ['name' => '订单金额', 'text' => $info['pay_money']],
  1218. 'status' => ['name' => '状态', 'text' => '待收货'],
  1219. ],
  1220. 'click_type' => 'payload',
  1221. 'url' => '/pages/order/detail?id=' . $id,
  1222. ];
  1223. if(!PushService::make()->pushMessageByUser($info['user_id'], $params, 0)){
  1224. DB::rollBack();
  1225. $this->error = PushService::make()->getError();
  1226. return false;
  1227. }
  1228. DB::commit();
  1229. $this->error = 2673;
  1230. return true;
  1231. } else {
  1232. DB::rollBack();
  1233. $this->error = 2672;
  1234. return false;
  1235. }
  1236. } catch (\Exception $exception){
  1237. DB::rollBack();
  1238. $this->error = $exception->getMessage();
  1239. return false;
  1240. }
  1241. }
  1242. /**
  1243. * 接单
  1244. * @return bool
  1245. */
  1246. public function picker()
  1247. {
  1248. $params = request()->all();
  1249. $id = isset($params['id']) ? $params['id'] : 0;
  1250. $mechId = isset($params['mech_id']) ? intval($params['mech_id']) : 0;
  1251. $merchId = isset($params['merch_id']) ? intval($params['merch_id']) : 0;
  1252. $info = $this->model->with(['mechanic','merchant'])
  1253. ->where(['id' => $id, 'mark' => 1])
  1254. ->select(['id','user_id','order_no','merch_id','source_id','pay_money','reception_at','coupon_id','status','refund_status','pay_time','appoint_time'])
  1255. ->first();
  1256. $status = isset($info['status']) ? $info['status'] : 0;
  1257. $merchant = isset($info['merchant']) ? $info['merchant'] : [];
  1258. $merchType = isset($merchant['type']) ? $merchant['type'] : 1;
  1259. if (!$id || empty($info)) {
  1260. $this->error = 2636;
  1261. return false;
  1262. }
  1263. if ($status != 2) {
  1264. $this->error = 2668;
  1265. return false;
  1266. }
  1267. // 验证技师或个体商家是否已经存在未完成订单
  1268. $checkId = $this->model->where(['status' =>3,'mark'=>1])->where(function($query) use($mechId, $merchId, $merchType){
  1269. // 技师
  1270. if($mechId){
  1271. $query->where(['source_id'=> $mechId]);
  1272. }
  1273. // 个体商家
  1274. else if($merchId){
  1275. $query->where(['merch_id'=> $merchId]);
  1276. }
  1277. })->value('id');
  1278. if(($mechId && $checkId) || ($merchType==2 && $checkId)){
  1279. $this->error = 2698;
  1280. return false;
  1281. }
  1282. // 处理
  1283. DB::beginTransaction();
  1284. if ($this->model->where(['id' => $id])->update(['status' => 3, 'update_time' => time()])) {
  1285. $params = [
  1286. 'title' => "订单成功接单通知",
  1287. 'body' => "您的订单已被接单,请即时查看订单进度",
  1288. 'type' => 2, // 1-公告通知,2-订单通知,3-交易通知,4-其他
  1289. 'content' => [
  1290. 'order_no' => ['name' => '订单号', 'text' => $info['order_no']],
  1291. 'time' => ['name' => '下单时间', 'text' => $info['pay_time']],
  1292. 'appoint_time' => ['name' => '预约时间', 'text' => $info['appoint_time']],
  1293. 'picker_time' => ['name' => '接单时间', 'text' => date('Y-m-d H:i:s')],
  1294. 'mechanic' => [],
  1295. 'money' => ['name' => '订单金额', 'text' => $info['pay_money']],
  1296. 'status' => ['name' => '状态', 'text' => '待服务'],
  1297. ],
  1298. 'click_type' => 'payload',
  1299. 'url' => '/pages/order/detail?id=' . $id,
  1300. ];
  1301. $mechanic = isset($info['mechanic'])? $info['mechanic'] : [];
  1302. $code = isset($mechanic['code'])? $mechanic['code'] : '';
  1303. if($code){
  1304. $params['content']['mechanic'] = ['name' => '接单技师', 'text' => "{$code}号技师"];
  1305. }
  1306. if(!PushService::make()->pushMessageByUser($info['user_id'], $params, 0)){
  1307. DB::rollBack();
  1308. $this->error = PushService::make()->getError();
  1309. return false;
  1310. }
  1311. DB::commit();
  1312. $this->error = 2674;
  1313. return true;
  1314. } else {
  1315. DB::rollBack();
  1316. $this->error = 2675;
  1317. return false;
  1318. }
  1319. }
  1320. /**
  1321. * 接单/上钟
  1322. * @return bool
  1323. */
  1324. public function inService()
  1325. {
  1326. $params = request()->all();
  1327. $id = isset($params['id']) ? $params['id'] : 0;
  1328. $mechId = isset($params['mech_id']) ? intval($params['mech_id']) : 0;
  1329. $merchId = isset($params['merch_id']) ? intval($params['merch_id']) : 0;
  1330. $info = $this->model->with(['mechanic'])->where(['id' => $id, 'mark' => 1])
  1331. ->select(['id','user_id','order_no','merch_id','source_id','pay_money','reception_at','coupon_id','status','is_service','refund_status','pay_time'])
  1332. ->first();
  1333. $status = isset($info['status']) ? $info['status'] : 0;
  1334. $isService = isset($info['is_service']) ? $info['is_service'] : 0;
  1335. $orderMechId = isset($info['source_id']) ? $info['source_id'] : 0;
  1336. $orderMerchId = isset($info['merch_id']) ? $info['merch_id'] : 0;
  1337. if (!$id || empty($info)) {
  1338. $this->error = 2636;
  1339. return false;
  1340. }
  1341. // if($mechId != $orderMechId && $merchId != $orderMerchId){
  1342. // $this->error = 2667;
  1343. // return false;
  1344. // }
  1345. if ($status != 3 || $isService == 1) {
  1346. $this->error = 2668;
  1347. return false;
  1348. }
  1349. // 处理
  1350. DB::beginTransaction();
  1351. if ($this->model->where(['id' => $id])->update(['is_service' => 1, 'update_time' => time()])) {
  1352. $params = [
  1353. 'title' => "订单开始服务通知",
  1354. 'body' => "您的订单已开始服务,请即时查看进度",
  1355. 'type' => 2, // 1-公告通知,2-订单通知,3-交易通知,4-其他
  1356. 'content' => [
  1357. 'order_no' => ['name' => '订单号', 'text' => $info['order_no']],
  1358. 'time' => ['name' => '下单时间', 'text' => $info['pay_time']],
  1359. 'picker_time' => ['name' => '开始时间', 'text' => date('Y-m-d H:i:s')],
  1360. 'mechanic' => [],
  1361. 'money' => ['name' => '订单金额', 'text' => $info['pay_money']],
  1362. 'status' => ['name' => '状态', 'text' => '服务中'],
  1363. ],
  1364. 'click_type' => 'payload',
  1365. 'url' => '/pages/order/detail?id=' . $id,
  1366. ];
  1367. $mechanic = isset($info['mechanic'])? $info['mechanic'] : [];
  1368. $code = isset($mechanic['code'])? $mechanic['code'] : '';
  1369. if($code){
  1370. $params['content']['mechanic'] = ['name' => '服务技师', 'text' => "{$code}号技师"];
  1371. }
  1372. if(!PushService::make()->pushMessageByUser($info['user_id'], $params, 0)){
  1373. DB::rollBack();
  1374. $this->error = PushService::make()->getError();
  1375. return false;
  1376. }
  1377. DB::commit();
  1378. $this->error = 1003;
  1379. return true;
  1380. } else {
  1381. DB::rollBack();
  1382. $this->error = 1002;
  1383. return false;
  1384. }
  1385. }
  1386. /**
  1387. * 收货/已完成
  1388. * @return bool
  1389. */
  1390. public function complete($userId, $params)
  1391. {
  1392. $id = isset($params['id']) ? $params['id'] : 0;
  1393. $merchId = isset($params['merch_id']) ? $params['merch_id'] : 0;
  1394. $info = $this->model->with(['goods'])
  1395. ->where(['id' => $id, 'mark' => 1])
  1396. ->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'])
  1397. ->first();
  1398. $status = isset($info['status']) ? $info['status'] : 0;
  1399. $orderUserId = isset($info['user_id']) ? $info['user_id'] : 0;
  1400. $orderMerchId = isset($info['merch_id']) ? $info['merch_id'] : 0;
  1401. $orderMechId = isset($info['source_id']) ? $info['source_id'] : 0;
  1402. $orderType = isset($info['type']) ? $info['type'] : 0;
  1403. $payMoney = isset($info['pay_money']) ? $info['pay_money'] : 0;
  1404. $goods = isset($info['goods'])? $info['goods'] : [];
  1405. if (!$id || empty($info)) {
  1406. $this->error = 2636;
  1407. return false;
  1408. }
  1409. // 非法操作
  1410. if($userId && $merchId != $orderMerchId && $orderUserId != $userId){
  1411. $this->error = 2667;
  1412. return false;
  1413. }
  1414. // 订单状态
  1415. if (($userId && $status != 3)||(!$userId && !in_array($status,[2,3]))) {
  1416. $this->error = 2668;
  1417. return false;
  1418. }
  1419. // 限制操作订单类型
  1420. if(!in_array($orderType, [1,2,6])){
  1421. $this->error = 2681;
  1422. return false;
  1423. }
  1424. // TODO 确认数据处理
  1425. DB::beginTransaction();
  1426. // 更新订单状态
  1427. if (!$this->model->where(['id' => $id])->update(['status' => 4, 'update_time' => time()])) {
  1428. DB::rollBack();
  1429. $this->error = 2678;
  1430. return false;
  1431. }
  1432. // 更新商品/服务销量
  1433. if($goods){
  1434. foreach($goods as $item){
  1435. $num = isset($item['num'])? $item['num'] : 0;
  1436. if($num>0){
  1437. GoodsModel::where(['id'=> $item['goods_id'],'mark'=>1])->update([
  1438. 'sales'=> DB::raw("sales + {$num}"),'update_time'=> time()
  1439. ]);
  1440. }
  1441. }
  1442. }
  1443. // 服务订单统计处理
  1444. if($orderType == 2){
  1445. // 更新技师服务订单,接单统计数据
  1446. $serviceCount = $this->model->where(['user_id'=> $orderUserId,'source_id'=> $orderMechId,'type'=>2,'status'=>4,'mark'=>1])->count('id');
  1447. $updateData = ['order_total'=> DB::raw("order_total + 1"),'update_time'=>time()];
  1448. if($serviceCount<=1){
  1449. $updateData['service_num'] = DB::raw("service_num + 1");
  1450. }
  1451. if($orderMechId && !MechanicModel::where(['id'=>$orderMechId,'mark'=> 1])->update($updateData)){
  1452. DB::rollBack();
  1453. $this->error = 2682;
  1454. return false;
  1455. }
  1456. // 更新商家服务订单,统计数据
  1457. $updateData = ['service_order_num'=> DB::raw("service_order_num + 1"),'service_order_total'=> DB::raw("service_order_total + {$payMoney}"),'update_time'=>time()];
  1458. if($orderMechId && !MerchantModel::where(['id'=>$orderMerchId,'mark'=> 1])->update($updateData)){
  1459. DB::rollBack();
  1460. $this->error = 2682;
  1461. return false;
  1462. }
  1463. }
  1464. // 店内订单结算
  1465. $balance = MerchantModel::where(['id'=> $orderMerchId,'mark'=>1])->value('balance');
  1466. if ($orderType == 6){
  1467. // 商家入账
  1468. $settleRate = ConfigService::make()->getConfigByCode('merch_settle_rate');
  1469. $settleRate = $settleRate>0? min(100, $settleRate) : 100;
  1470. $settleMoney = moneyFormat($payMoney * $settleRate/100, 2);
  1471. $updateData = ['balance'=> DB::raw("balance + {$settleMoney}"),'update_time'=>time()];
  1472. if($settleMoney>0 && !MerchantModel::where(['id'=> $orderMerchId,'mark'=>1])->update($updateData)){
  1473. DB::rollBack();
  1474. $this->error = 2683;
  1475. return false;
  1476. }
  1477. // 流水记录
  1478. $log = [
  1479. 'user_id'=> 0,
  1480. 'merch_id'=> $orderMerchId,
  1481. 'source_uid'=> $orderUserId,
  1482. 'source_order_no'=> isset($info['order_no'])? $info['order_no'] :'',
  1483. 'type'=> 3,
  1484. 'coin_type'=> 2,
  1485. 'user_type'=> 2,
  1486. 'money'=> $settleMoney,
  1487. 'balance'=>$balance? $balance : 0.00,
  1488. 'create_time'=> time(),
  1489. 'update_time'=> time(),
  1490. 'remark'=> '商家店内订单收入',
  1491. 'status'=>1,
  1492. 'mark'=>1
  1493. ];
  1494. if(!AccountLogModel::insertGetId($log)){
  1495. DB::rollBack();
  1496. $this->error = 2641;
  1497. return false;
  1498. }
  1499. // 平台抽成入账,财务统计
  1500. $financeMoney = floatval($payMoney - $settleMoney);
  1501. if($financeMoney>0){
  1502. $log = [
  1503. 'user_id'=> 0,
  1504. 'merch_id'=> 0,
  1505. 'source_uid'=> $orderUserId,
  1506. 'source_order_no'=> $info['order_no'],
  1507. 'type'=> 13,
  1508. 'coin_type'=> 2,
  1509. 'user_type'=> 5,
  1510. 'money'=> $financeMoney,
  1511. 'balance'=> 0,
  1512. 'create_time'=> time(),
  1513. 'update_time'=> time(),
  1514. 'remark'=> '平台店内订单收入',
  1515. 'status'=>1,
  1516. 'mark'=>1
  1517. ];
  1518. if(!AccountLogModel::insertGetId($log)){
  1519. DB::rollBack();
  1520. $this->error = 2641;
  1521. return false;
  1522. }
  1523. FinanceService::make()->saveLog(0,$financeMoney, 1, 1);
  1524. }
  1525. }
  1526. // 服务订单结算
  1527. else if(in_array($orderType, [1,2])){
  1528. // 计算服务订单分销佣金和代理佣金
  1529. if(!$result = FinanceService::make()->settleOrder($info, $userId)){
  1530. DB::rollBack();
  1531. $this->error = FinanceService::make()->getError();
  1532. return false;
  1533. }
  1534. // 商家入账
  1535. $settleMoney = isset($result['merch_money'])? $result['merch_money'] : 0;
  1536. $updateData = [
  1537. 'balance'=> DB::raw("balance + {$settleMoney}"),
  1538. 'service_order_num'=>DB::raw("service_order_num + 1"),
  1539. 'service_order_total'=>DB::raw("service_order_total + {$payMoney}"),
  1540. 'update_time'=>time()
  1541. ];
  1542. if($settleMoney>0 && !MerchantModel::where(['id'=> $orderMerchId,'mark'=>1])->update($updateData)){
  1543. DB::rollBack();
  1544. $this->error = 2683;
  1545. return false;
  1546. }
  1547. $log = [
  1548. 'user_id'=> 0,
  1549. 'merch_id'=> $orderMerchId,
  1550. 'source_uid'=> $orderUserId,
  1551. 'source_order_no'=> isset($info['order_no'])? $info['order_no'] :'',
  1552. 'type'=> 3,
  1553. 'coin_type'=> 2,
  1554. 'user_type'=> 2,
  1555. 'money'=> $settleMoney,
  1556. 'balance'=>$balance? $balance : 0.00,
  1557. 'create_time'=> time(),
  1558. 'update_time'=> time(),
  1559. 'remark'=> '商家订单收入',
  1560. 'status'=>1,
  1561. 'mark'=>1
  1562. ];
  1563. if(!AccountLogModel::insertGetId($log)){
  1564. DB::rollBack();
  1565. $this->error = 2641;
  1566. return false;
  1567. }
  1568. // 平台入账,财务统计
  1569. $financeMoney = isset($result['platform_money'])? $result['platform_money'] : 0;
  1570. if($financeMoney>0){
  1571. FinanceService::make()->saveLog(0,$financeMoney, 1, 1);
  1572. }
  1573. $log = [
  1574. 'user_id'=> 0,
  1575. 'merch_id'=> 0,
  1576. 'source_uid'=> $orderUserId,
  1577. 'source_order_no'=> isset($info['order_no'])? $info['order_no'] :'',
  1578. 'type'=> 13,
  1579. 'coin_type'=> 2,
  1580. 'user_type'=> 5,
  1581. 'money'=> $financeMoney,
  1582. 'balance'=> 0,
  1583. 'create_time'=> time(),
  1584. 'update_time'=> time(),
  1585. 'remark'=> '平台订单收入',
  1586. 'status'=>1,
  1587. 'mark'=>1
  1588. ];
  1589. if(!AccountLogModel::insertGetId($log)){
  1590. DB::rollBack();
  1591. $this->error = 2641;
  1592. return false;
  1593. }
  1594. // 技师累计
  1595. if($orderMechId){
  1596. $updateData = [
  1597. 'order_total'=> DB::raw("order_total + 1"),
  1598. 'service_num'=>DB::raw("service_num + 1"),
  1599. 'update_time'=>time()
  1600. ];
  1601. MechanicModel::where(['id'=> $orderMechId,'mark'=>1])->update($updateData);
  1602. }
  1603. }
  1604. // 消息推送
  1605. $params = [
  1606. 'title' => "订单完成通知",
  1607. 'body' => "您的订单已完成,请即时查看进度并给予评论",
  1608. 'type' => 2, // 1-公告通知,2-订单通知,3-交易通知,4-其他
  1609. 'content' => [
  1610. 'order_no' => ['name' => '订单号', 'text' => $info['order_no']],
  1611. 'time' => ['name' => '下单时间', 'text' => $info['pay_time']],
  1612. 'picker_time' => ['name' => '确认时间', 'text' => date('Y-m-d H:i:s')],
  1613. 'mechanic' => [],
  1614. 'money' => ['name' => '订单金额', 'text' => $info['pay_money']],
  1615. 'status' => ['name' => '状态', 'text' => '已完成'],
  1616. ],
  1617. 'click_type' => 'payload',
  1618. 'url' => '/pages/order/detail?id=' . $id,
  1619. ];
  1620. $mechanic = isset($info['mechanic'])? $info['mechanic'] : [];
  1621. $code = isset($mechanic['code'])? $mechanic['code'] : '';
  1622. if($code){
  1623. $params['content']['mechanic'] = ['name' => '服务技师', 'text' => "{$code}号技师"];
  1624. }
  1625. if(!PushService::make()->pushMessageByUser($info['user_id'], $params, 0)){
  1626. DB::rollBack();
  1627. $this->error = PushService::make()->getError();
  1628. return false;
  1629. }
  1630. DB::commit();
  1631. $this->error = 1002;
  1632. return true;
  1633. }
  1634. /**
  1635. * 评论
  1636. * @return bool
  1637. */
  1638. public function comment($userId, $params)
  1639. {
  1640. $orderId = isset($params['order_id']) ? $params['order_id'] : 0;
  1641. $info = $this->model->where(['id' => $orderId, 'mark' => 1])->first();
  1642. $status = isset($info['status']) ? $info['status'] : 0;
  1643. if (!$orderId || empty($info)) {
  1644. $this->error = 2689;
  1645. return false;
  1646. }
  1647. if (!in_array($status, [3, 4])) {
  1648. $this->error = 2668;
  1649. return false;
  1650. }
  1651. $score = isset($params['score'])? intval($params['score']) : 0;
  1652. $score = $score>0 && $score<=5? $score : 0;
  1653. if($score<=0){
  1654. $this->error = 2691;
  1655. return false;
  1656. }
  1657. // 是否已经评论
  1658. $comment = MerchantCommentModel::where(['user_id'=> $userId,'order_id'=> $orderId,'mark'=>1])
  1659. ->select(['id','status'])
  1660. ->first();
  1661. $status = isset($comment['status'])? $comment['status'] : 0;
  1662. $commentId = isset($comment['id'])? $comment['id'] : 0;
  1663. if($comment && $status == 1){
  1664. $this->error = 2690;
  1665. return false;
  1666. }
  1667. $content = isset($params['content'])? $params['content'] : '';
  1668. $content = $content? MessageService::make()->filterMessage($content) : '';
  1669. $albums = isset($params['albums'])? get_format_images($params['albums']) : '';
  1670. $merchId = isset($info['merch_id'])? $info['merch_id'] : 0;
  1671. $publishTime = ConfigService::make()->getConfigByCode('publish_auto_check_time');
  1672. $publishTime = $publishTime? $publishTime : 0;
  1673. $publishAt = date('Y-m-d H:i:s', time() + $publishTime * 60);
  1674. $orderGoodsId = OrderGoodsModel::where(['order_no'=> $info['order_no'],'status'=>1,'mark'=>1])->pluck('goods_id');
  1675. $orderGoodsId = $orderGoodsId? $orderGoodsId->toArray() : [];
  1676. $data = [
  1677. 'user_id'=> $userId,
  1678. 'order_id'=> $orderId,
  1679. 'merch_id'=> $merchId,
  1680. 'mech_id'=> isset($info['source_id'])? $info['source_id'] : 0,
  1681. 'reply_id'=> isset($params['reply_id'])? $params['reply_id'] : 0,
  1682. 'content'=> $content,
  1683. 'albums'=> $albums,
  1684. 'score'=> $score,
  1685. 'goods'=> $orderGoodsId? implode(',', $orderGoodsId) : '',
  1686. 'update_time'=> time(),
  1687. 'publish_time'=> $publishAt,
  1688. 'status'=> 1,
  1689. ];
  1690. DB::beginTransaction();
  1691. if($comment){
  1692. if(!MerchantCommentModel::where(['id'=> $commentId])->update($data)){
  1693. DB::rollBack();
  1694. $this->error = 2693;
  1695. return false;
  1696. }
  1697. }else{
  1698. $data['create_time'] = time();
  1699. if(!$commentId = MerchantCommentModel::insertGetId($data)){
  1700. DB::rollBack();
  1701. $this->error = 2693;
  1702. return false;
  1703. }
  1704. }
  1705. $updateData = ['score_rate'=> DB::raw("(score_rate+{$score})/2"),'update_time'=>time()];
  1706. if(!MerchantModel::where(['id'=> $merchId])->update($updateData)){
  1707. DB::rollBack();
  1708. $this->error = 2693;
  1709. return false;
  1710. }
  1711. DB::commit();
  1712. $this->error = lang('2692',['time'=> $publishTime? $publishTime:'0']);
  1713. return ['id'=> $commentId];
  1714. }
  1715. /**
  1716. * 隐藏订单
  1717. * @return false
  1718. */
  1719. public function hide()
  1720. {
  1721. $params = request()->all();
  1722. $id = isset($params['id']) ? $params['id'] : 0;
  1723. $info = $this->model->where(['id' => $id, 'mark' => 1])
  1724. ->select(['id','user_id','order_no','merch_id','source_id','status','user_delete'])
  1725. ->first();
  1726. if (!$id || empty($info)) {
  1727. $this->error = 2636;
  1728. return false;
  1729. }
  1730. $userDelete = isset($info['user_delete'])? $info['user_delete'] : 0;
  1731. if($userDelete == 2){
  1732. $this->error = 2235;
  1733. return false;
  1734. }
  1735. if($this->model->where(['id'=> $id])->update(['user_delete'=>2,'update_time'=>time()]))
  1736. {
  1737. $this->error = 2236;
  1738. return true;
  1739. }else{
  1740. $this->error = 2237;
  1741. return false;
  1742. }
  1743. }
  1744. }