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