OrderService.php 74 KB

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