OrderService.php 74 KB

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