OrderService.php 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524
  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\CartModel;
  14. use App\Models\GoodsModel;
  15. use App\Models\GoodsSkuModel;
  16. use App\Models\MemberModel;
  17. use App\Models\OrderGoodsModel;
  18. use App\Models\OrderModel;
  19. use App\Models\StoreModel;
  20. use App\Services\BaseService;
  21. use App\Services\ConfigService;
  22. use App\Services\Kd100Service;
  23. use App\Services\PaymentService;
  24. use App\Services\RedisService;
  25. use Illuminate\Support\Facades\DB;
  26. /**
  27. * 订单-服务类
  28. * @author laravel开发员
  29. * @since 2020/11/11
  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. */
  41. public function __construct()
  42. {
  43. $this->model = new OrderModel();
  44. }
  45. /**
  46. * 静态入口
  47. */
  48. public static function make()
  49. {
  50. if (!self::$instance) {
  51. self::$instance = new static();
  52. }
  53. return self::$instance;
  54. }
  55. /**
  56. * 订单列表
  57. * @param $params
  58. * @param int $pageSize
  59. * @return array
  60. */
  61. public function getDataList($params, $pageSize = 15)
  62. {
  63. $model = $this->getQuery($params);
  64. // 数据
  65. $list = $model->where(function ($query) use ($params) {
  66. $status = isset($params['status']) ? $params['status'] : 0;
  67. if ($status > 0 && is_array($status)) {
  68. $query->whereIn('a.status', $status)->where('a.refund_status', 0);
  69. } else if ($status == 6) {
  70. $query->where('a.status', '>', 1)->where('a.refund_status', '>', 0);
  71. } else if ($status > 0) {
  72. $query->where('a.status', $status)->where('a.refund_status', 0);
  73. }
  74. })->select(['a.*'])
  75. ->orderBy('a.id', 'desc')
  76. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  77. $list = $list ? $list->toArray() : [];
  78. if ($list) {
  79. $statusArr = [1 => '待支付', 2 => '待发货', 3 => '待收货', 4 => '确认收货'];
  80. foreach ($list['data'] as &$item) {
  81. $item['create_time'] = $item['create_time'] ? dateFormat(strtotime($item['create_time']), 'Y-m-d') : '';
  82. $status = isset($item['status']) ? $item['status'] : 0;
  83. $item['status_text'] = '待支付';
  84. if ($status) {
  85. $item['status_text'] = isset($statusArr[$status]) ? $statusArr[$status] : '';
  86. }
  87. if ($item['refund_status'] > 0) {
  88. $item['status_text'] = '退款/售后';
  89. }
  90. $item['goods'] = isset($item['goods']) && $item['goods'] ? $item['goods'] : [];
  91. $item['real_total'] = $item['pay_total'];
  92. $item['pay_total'] = moneyFormat($item['pay_total'] + $item['delivery_fee'], 2);
  93. }
  94. unset($item);
  95. }
  96. return [
  97. 'pageSize' => $pageSize,
  98. 'total' => isset($list['total']) ? $list['total'] : 0,
  99. 'list' => isset($list['data']) ? $list['data'] : []
  100. ];
  101. }
  102. /**
  103. * 查询条件
  104. * @param $params
  105. * @return mixed
  106. */
  107. public function getQuery($params)
  108. {
  109. $where = ['a.is_hide' => 0,'a.main_no'=>'', 'a.mark' => 1];
  110. return $this->model->from('orders as a')
  111. ->with(['orderGoods', 'store'])
  112. ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
  113. ->where($where)
  114. ->where(function ($query) use ($params) {
  115. $userId = isset($params['user_id']) ? intval($params['user_id']) : 0;
  116. if ($userId > 0) {
  117. $query->where('a.user_id', $userId);
  118. }
  119. // 订单类型
  120. $type = isset($params['type']) ? intval($params['type']) : 0;
  121. if ($type > 0) {
  122. $query->where('a.type', $type);
  123. }
  124. })
  125. ->where(function ($query) use ($params) {
  126. $keyword = isset($params['keyword']) ? $params['keyword'] : '';
  127. if ($keyword) {
  128. $query->where('a.order_no', 'like', "%{$keyword}%")
  129. ->orWhere('b.mobile', 'like', "%{$keyword}%");
  130. }
  131. });
  132. }
  133. /**
  134. * 订单详情
  135. * @param $id
  136. */
  137. public function getOrderInfo($id, $no = '')
  138. {
  139. $where = ['a.order_no' => $no, 'a.id' => $id, 'a.mark' => 1];
  140. if ($no) {
  141. unset($where['a.id']);
  142. } else {
  143. unset($where['a.order_no']);
  144. }
  145. $statusArr = [1 => '待支付', 2 => '待发货', 3 => '待收货', 4 => '已完成'];
  146. $info = $this->model->from('orders as a')
  147. ->with(['orderGoods', 'store'])
  148. ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
  149. ->where($where)
  150. ->select(['a.*'])
  151. ->first();
  152. if ($info) {
  153. $info = $info->toArray();
  154. $info['create_time'] = $info['create_time'] ? datetime($info['create_time'], 'Y-m-d H:i:s') : '';
  155. $info['pay_at'] = $info['pay_at'] ? datetime(strtotime($info['pay_at']), 'Y-m-d H:i:s') : '';
  156. $info['receiver_mobile_text'] = $info['receiver_mobile'] ? format_mobile($info['receiver_mobile']) : '';
  157. $info['real_total'] = $info['pay_total'];
  158. $info['pay_total'] = moneyFormat($info['pay_total'] + $info['delivery_fee'], 2);
  159. $status = isset($info['status']) ? $info['status'] : 0;
  160. $info['status_text'] = '待支付';
  161. if ($status) {
  162. $info['status_text'] = isset($statusArr[$status]) ? $statusArr[$status] : '';
  163. }
  164. }
  165. return $info;
  166. }
  167. /**
  168. * 创建订单
  169. * @param $userId 用户
  170. * @param $params 参数
  171. * @return array|false
  172. */
  173. public function createOrder($userId, $params)
  174. {
  175. $type = isset($params['type']) && $params['type'] ? $params['type'] : 1;
  176. $submitType = isset($params['submit_type']) && $params['submit_type'] ? $params['submit_type'] : '';
  177. $addressId = isset($params['address_id']) && $params['address_id'] ? $params['address_id'] : 0;
  178. $goods = isset($params['goods']) && $params['goods'] ? $params['goods'] : [];
  179. $ids = $goods ? array_column($goods, 'id') : [];
  180. // 参数验证
  181. if (empty($goods) || empty($ids)) {
  182. $this->error = '商品参数不为空';
  183. return false;
  184. }
  185. if ($addressId <= 0) {
  186. $this->error = '请选择收货地址';
  187. return false;
  188. }
  189. // 缓存锁
  190. $cacheLockKey = "caches:orders:submit_lock:{$userId}";
  191. if (RedisService::get($cacheLockKey)) {
  192. $this->error = '订单处理中~';
  193. return false;
  194. }
  195. // 用户信息
  196. RedisService::set($cacheLockKey, ['params' => $params, 'user_id' => $userId], rand(3, 5));
  197. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  198. ->select(['id', 'openid','nickname','member_level','parent_id','point_id','points', 'buy_type','property','balance', 'bd_score', 'status'])
  199. ->first();
  200. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  201. $openid = isset($userInfo['openid']) ? $userInfo['openid'] : 0;
  202. $buyType = isset($userInfo['buy_type']) ? $userInfo['buy_type'] : 0;
  203. $bdScore = isset($userInfo['bd_score']) ? $userInfo['bd_score'] : 0;
  204. $discountPoint = isset($userInfo['discount_point']) ? $userInfo['discount_point'] : 0; // 折扣
  205. if (empty($userInfo) || $status != 1) {
  206. $this->error = 1045;
  207. return false;
  208. }
  209. if (empty($openid)) {
  210. $this->error = 1042;
  211. return false;
  212. }
  213. // 商品数据
  214. $orderNo = get_order_num('JK');
  215. $result = GoodsService::make()->getOrderGoods($ids, $goods, $userId, $orderNo, $discountPoint);
  216. if (empty($result)) {
  217. RedisService::clear($cacheLockKey);
  218. $this->error = GoodsService::make()->getError();
  219. return false;
  220. }
  221. $orderGoods = isset($result['goods']) ? $result['goods'] : [];
  222. $goodsTotal = isset($result['goods_total']) ? $result['goods_total'] : 0; // 商品总价
  223. $orderTotal = isset($result['order_total']) ? $result['order_total'] : 0; // 订单结算金额(折后)
  224. $bdScoreTotal = isset($result['bd_score_total']) ? $result['bd_score_total'] : 0; // 报单积分
  225. $profitTotal = isset($result['profit_total']) ? $result['profit_total'] : 0; // 利润
  226. $discountTotal = isset($result['discount_total']) ? $result['discount_total'] : 0; // 折扣金额
  227. $orderCount = isset($result['count']) ? $result['count'] : 0;
  228. $deliveryFee = isset($result['delivery_fee']) ? $result['delivery_fee'] : 0; // 运费
  229. $storeId = isset($result['store_id']) ? $result['store_id'] : 0; // 企业/商家
  230. if (empty($orderGoods)) {
  231. RedisService::clear($cacheLockKey);
  232. $this->error = '获取订单商品错误~';
  233. return false;
  234. }
  235. if ($orderTotal <= 0) {
  236. RedisService::clear($cacheLockKey);
  237. $this->error = '订单金额错误~';
  238. return false;
  239. }
  240. if ($orderCount <= 0) {
  241. RedisService::clear($cacheLockKey);
  242. $this->error = '订单商品数量错误~';
  243. return false;
  244. }
  245. // 创业大礼包
  246. $mealId = 0;
  247. if ($type == 2) {
  248. $mealId = isset($ids[0]) ? $ids[0] : 0;
  249. if ($buyType != $mealId) {
  250. RedisService::clear($cacheLockKey);
  251. $this->error = '该礼包您暂时不满足购买条件';
  252. return false;
  253. }
  254. // 报单积分是否够
  255. if ($bdScore < $bdScoreTotal) {
  256. RedisService::clear($cacheLockKey);
  257. $this->error = '抱歉,您的报单积分不足';
  258. return false;
  259. }
  260. // 是否购买过
  261. $buyLimit = ConfigService::make()->getConfigByCode('business_buy_limit', 0);
  262. $buyLimit = $buyLimit>0?$buyLimit:0;
  263. if($buyLimit>0){
  264. $checkOrderCount = $this->checkBusinessOrder($userId, $mealId);
  265. if ($checkOrderCount >= $buyLimit) {
  266. RedisService::clear($cacheLockKey);
  267. $this->error = $buyLimit>1?"抱歉该创业礼包仅限购买{$buyLimit}次":'抱歉,您已经购买过该礼包';
  268. return false;
  269. }
  270. }
  271. }
  272. // 收货地址信息
  273. $addressInfo = MemberAddressService::make()->getBindInfo($userId, $addressId);
  274. $realname = isset($addressInfo['realname']) ? $addressInfo['realname'] : '';
  275. $mobile = isset($addressInfo['mobile']) ? $addressInfo['mobile'] : '';
  276. $area = isset($addressInfo['area']) ? $addressInfo['area'] : '';
  277. $address = isset($addressInfo['address']) ? $addressInfo['address'] : '';
  278. if (empty($addressInfo) || empty($realname) || empty($mobile) || empty($area) || empty($address)) {
  279. RedisService::clear($cacheLockKey);
  280. $this->error = '收货地址信息错误,请核对后重试~';
  281. return false;
  282. }
  283. // 是否开启分账功能
  284. $payTotal = moneyFormat($orderTotal + $deliveryFee, 2); // 含运费支付金额
  285. if (env('PAY_DEBUG')) {
  286. $payTotal = 0.01;
  287. }
  288. // 订单数据
  289. $order = [
  290. 'order_no' => $orderNo,
  291. 'user_id' => $userId,
  292. 'store_id' => $storeId,
  293. 'meal_id' => $mealId,
  294. 'type' => $type,
  295. 'total' => $goodsTotal, // 商品总价
  296. 'num' => $orderCount,
  297. 'bd_score' => $bdScoreTotal, // 折扣后商品总价(不含运费)
  298. 'profit_total' => $profitTotal, // 折扣后商品总价(不含运费)
  299. 'pay_money' => $orderTotal, // 折扣后商品总价(不含运费)
  300. 'pay_total' => $type==2 && $bdScoreTotal>0?moneyFormat($orderTotal + $bdScoreTotal,2):$orderTotal, // 折扣后商品总价(不含运费)
  301. 'pay_status' => $type==2 && $bdScoreTotal>0? 30 : 10, // 折扣后商品总价(不含运费)
  302. 'discount_point' => $discountPoint,
  303. 'discount_total' => $discountTotal, // 折扣金额
  304. 'delivery_fee' => $deliveryFee, // 运费
  305. 'receiver_name' => $realname,
  306. 'receiver_mobile' => $mobile,
  307. 'receiver_area' => $area,
  308. 'receiver_address' => $address,
  309. 'create_time' => time(),
  310. 'update_time' => time(),
  311. 'status' => 1,
  312. 'mark' => 1,
  313. ];
  314. // 订单处理
  315. DB::beginTransaction();
  316. if (!$orderId = $this->model->insertGetId($order)) {
  317. DB::rollBack();
  318. $this->error = '创建订单失败';
  319. RedisService::clear($cacheLockKey);
  320. return false;
  321. }
  322. // 订单商品
  323. if ($orderGoods && !OrderGoodsModel::insert($orderGoods)) {
  324. DB::rollBack();
  325. $this->error = '处理订单商品错误';
  326. RedisService::clear($cacheLockKey);
  327. return false;
  328. }
  329. // 创业礼包分单
  330. if ($type == 2) {
  331. $data = $order;
  332. $data['total'] = moneyFormat($data['total'] / 6);
  333. $data['bd_score'] = moneyFormat($bdScoreTotal / 6, 2);
  334. $data['profit_total'] = moneyFormat($profitTotal / 6, 2);
  335. $data['pay_total'] = moneyFormat($orderTotal / 6, 2);
  336. $data['pay_money'] = moneyFormat($order['pay_money'] / 6, 2);
  337. $subOrders = [];
  338. for ($i = 1; $i <= 6; $i++) {
  339. $data['order_no'] = get_order_num('BS');
  340. $data['main_no'] = $orderNo;
  341. if ($i == 6) {
  342. $data['total'] = round($order['total'] / 6, 2);
  343. $data['bd_score'] = round($bdScoreTotal / 6, 2);
  344. $data['profit_total'] = round($profitTotal / 6, 2);
  345. $data['pay_total'] = round($orderTotal / 6, 2);
  346. $data['pay_money'] = round($order['pay_money'] / 6, 2);
  347. }
  348. $subOrders[] = $data;
  349. }
  350. //
  351. if ($subOrders && !$this->model->insert($subOrders)) {
  352. DB::rollBack();
  353. $this->error = '处理商品订单失败';
  354. RedisService::clear($cacheLockKey);
  355. return false;
  356. }
  357. // 扣除报单积分
  358. if($bdScoreTotal>0){
  359. if(!MemberModel::where(['id'=>$userId])->update(['bd_score'=>DB::raw("bd_score - {$bdScoreTotal}"),'update_time'=>time()])){
  360. DB::rollBack();
  361. $this->error = '报单积分扣除失败';
  362. RedisService::clear($cacheLockKey);
  363. return false;
  364. }
  365. $data = [
  366. 'user_id'=>$userId,
  367. 'source_order_no'=>$orderNo,
  368. 'user_type'=> 1,
  369. 'account_type'=> 3, // 报单积分
  370. 'type'=> 1,
  371. 'money'=> -$bdScoreTotal,
  372. 'after_money'=>moneyFormat($bdScore - $bdScoreTotal,2),
  373. 'date'=>date('Y-m-d'),
  374. 'create_time'=>time(),
  375. 'remark'=> '创业礼包支付',
  376. 'status'=>1,
  377. 'mark'=>1
  378. ];
  379. if(!AccountLogModel::insertGetId($data)){
  380. Db::rollBack();
  381. $this->error = '付款处理失败';
  382. return false;
  383. }
  384. }
  385. }
  386. // 佣金数据
  387. $order['id'] = $orderId;
  388. if(!$commission = SettleService::make()->commissionCount($order,$orderGoods,$userInfo, $type)){
  389. Db::rollBack();
  390. $this->error = '订单处理失败';
  391. return false;
  392. }
  393. // 获取支付参数
  394. /* TODO 支付处理 */
  395. $payOrder = [
  396. 'type' => 1,
  397. 'order_no' => $orderNo,
  398. 'is_revenue' => isset($order['is_revenue'])?$order['is_revenue']:2,
  399. 'pay_money' => $payTotal,
  400. 'body' => '订单付款',
  401. 'openid' => $openid
  402. ];
  403. // 调起支付
  404. $payment = PaymentService::make()->minPay($userInfo, $payOrder, 'store');
  405. if (empty($payment)) {
  406. //DB::rollBack();
  407. RedisService::clear($cacheLockKey);
  408. $this->error = PaymentService::make()->getError();
  409. return false;
  410. }
  411. // 商品库存扣除
  412. if ($orderGoods) {
  413. foreach ($orderGoods as $item) {
  414. $id = isset($item['goods_id']) ? $item['goods_id'] : 0;
  415. $num = isset($item['num']) ? $item['num'] : 0;
  416. $skuId = isset($item['sku_id']) ? $item['sku_id'] : 0;
  417. if ($id && !GoodsModel::where(['id' => $id])->update(['stock' => DB::raw("stock - {$num}"), 'update_time' => time()])) {
  418. DB::rollBack();
  419. RedisService::clear($cacheLockKey);
  420. $this->error = '商品库存处理失败';
  421. return false;
  422. }
  423. if ($skuId && !GoodsSkuModel::where(['id' => $skuId])->update(['stock' => DB::raw("stock - {$num}"), 'update_time' => time()])) {
  424. DB::rollBack();
  425. RedisService::clear($cacheLockKey);
  426. $this->error = '商品库存处理失败';
  427. return false;
  428. }
  429. }
  430. // 清空购物车结算商品
  431. if($submitType == 'cart'){
  432. $skuIds = $goods ? array_column($goods, 'sku_id') : [];
  433. CartModel::whereIn('goods_id',$ids)->whereIn('sku_id',$skuIds)->where(['user_id'=>$userId,'mark'=>1])->update(['mark'=>0,'num'=>0,'update_time'=>time()]);
  434. RedisService::clear("caches:goods:cartCount:{$userId}");
  435. }
  436. }
  437. // 用户操作记录
  438. DB::commit();
  439. $this->error = '订单创建成功,请前往支付~';
  440. RedisService::clear($cacheLockKey);
  441. return [
  442. 'order_id' => $orderId,
  443. 'payment' => $payment,
  444. 'total' => $payOrder['pay_money'],
  445. 'pay_type' => 10,
  446. ];
  447. }
  448. /**
  449. * 自动复购
  450. * @param $userId 用户
  451. * @param $mealId 套餐ID
  452. * @return array|false
  453. */
  454. public function rebuyOrder($userId, $mealId)
  455. {
  456. try {
  457. $type = 2;
  458. $goods = ["id_{$mealId}"=>['id'=>$mealId,'sku_id'=>0,'num'=>1]];
  459. $ids = [$mealId];
  460. // 缓存锁
  461. $cacheLockKey = "caches:orders:submit_lock:{$userId}";
  462. if (RedisService::get($cacheLockKey)) {
  463. $this->error = '订单处理中~';
  464. return false;
  465. }
  466. // 用户信息
  467. RedisService::set($cacheLockKey, ['mealId' => $mealId, 'user_id' => $userId], rand(3, 5));
  468. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  469. ->select(['id', 'openid','nickname','member_level','parent_id','point_id','points', 'buy_type','property','balance', 'bd_score', 'status'])
  470. ->first();
  471. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  472. $openid = isset($userInfo['openid']) ? $userInfo['openid'] : 0;
  473. $points = isset($userInfo['points']) ? $userInfo['points'] : '';
  474. $bdScore = isset($userInfo['bd_score']) ? $userInfo['bd_score'] : 0;
  475. $balance = isset($userInfo['balance']) ? $userInfo['balance'] : 0;
  476. $discountPoint = isset($userInfo['discount_point']) ? $userInfo['discount_point'] : 0; // 折扣
  477. if (empty($userInfo) || $status != 1) {
  478. $this->error = 1045;
  479. return false;
  480. }
  481. if (empty($openid)) {
  482. $this->error = 1042;
  483. return false;
  484. }
  485. // 商品数据
  486. $orderNo = get_order_num('JK');
  487. $result = GoodsService::make()->getOrderGoods($ids, $goods, $userId, $orderNo, $discountPoint);
  488. if (empty($result)) {
  489. RedisService::clear($cacheLockKey);
  490. $this->error = GoodsService::make()->getError();
  491. return false;
  492. }
  493. $orderGoods = isset($result['goods']) ? $result['goods'] : [];
  494. $goodsTotal = isset($result['goods_total']) ? $result['goods_total'] : 0; // 商品总价
  495. $orderTotal = isset($result['order_total']) ? $result['order_total'] : 0; // 订单结算金额(折后)
  496. $bdScoreTotal = isset($result['bd_score_total']) ? $result['bd_score_total'] : 0; // 报单积分
  497. $profitTotal = isset($result['profit_total']) ? $result['profit_total'] : 0; // 利润
  498. $discountTotal = isset($result['discount_total']) ? $result['discount_total'] : 0; // 折扣金额
  499. $orderCount = isset($result['count']) ? $result['count'] : 0;
  500. $deliveryFee = isset($result['delivery_fee']) ? $result['delivery_fee'] : 0; // 运费
  501. $storeId = isset($result['store_id']) ? $result['store_id'] : 0; // 企业/商家
  502. if (empty($orderGoods)) {
  503. RedisService::clear($cacheLockKey);
  504. $this->error = '获取订单商品错误~';
  505. return false;
  506. }
  507. if ($orderTotal <= 0) {
  508. RedisService::clear($cacheLockKey);
  509. $this->error = '订单金额错误~';
  510. return false;
  511. }
  512. if ($orderCount <= 0) {
  513. RedisService::clear($cacheLockKey);
  514. $this->error = '订单商品数量错误~';
  515. return false;
  516. }
  517. // 报单积分是否够
  518. if ($bdScore < $bdScoreTotal) {
  519. RedisService::clear($cacheLockKey);
  520. $this->error = '抱歉,您的报单积分不足';
  521. return false;
  522. }
  523. // 是否购买过
  524. $buyLimit = ConfigService::make()->getConfigByCode('business_buy_limit', 0);
  525. $buyLimit = $buyLimit>0?$buyLimit:0;
  526. if($buyLimit>0){
  527. $checkOrderCount = $this->checkBusinessOrder($userId, $mealId);
  528. if ($checkOrderCount >= $buyLimit) {
  529. RedisService::clear($cacheLockKey);
  530. $this->error = $buyLimit>1?"抱歉该创业礼包仅限购买{$buyLimit}次":'抱歉,您已经购买过该礼包';
  531. return false;
  532. }
  533. }
  534. // 收货地址信息
  535. $addressInfo = MemberAddressService::make()->getBindInfo($userId);
  536. $realname = isset($addressInfo['realname']) ? $addressInfo['realname'] : '';
  537. $mobile = isset($addressInfo['mobile']) ? $addressInfo['mobile'] : '';
  538. $area = isset($addressInfo['area']) ? $addressInfo['area'] : '';
  539. $address = isset($addressInfo['address']) ? $addressInfo['address'] : '';
  540. if (empty($addressInfo) || empty($realname) || empty($mobile) || empty($area) || empty($address)) {
  541. RedisService::clear($cacheLockKey);
  542. $this->error = '收货地址信息错误,请核对后重试~';
  543. return false;
  544. }
  545. // 是否开启分账功能
  546. $payTotal = moneyFormat($orderTotal + $deliveryFee, 2); // 含运费支付金额
  547. if($balance < $payTotal){
  548. RedisService::clear($cacheLockKey);
  549. $this->error = "自动复购失败,您的余额不足";
  550. return false;
  551. }
  552. // 订单数据
  553. $order = [
  554. 'order_no' => $orderNo,
  555. 'user_id' => $userId,
  556. 'store_id' => $storeId,
  557. 'meal_id' => $mealId,
  558. 'type' => $type,
  559. 'total' => $goodsTotal, // 商品总价
  560. 'num' => $orderCount,
  561. 'bd_score' => $bdScoreTotal, // 折扣后商品总价(不含运费)
  562. 'profit_total' => $profitTotal, // 折扣后商品总价(不含运费)
  563. 'pay_money' => $orderTotal, // 折扣后商品总价(不含运费)
  564. 'pay_total' => $type==2 && $bdScoreTotal>0?moneyFormat($orderTotal + $bdScoreTotal,2):$orderTotal, // 折扣后商品总价(不含运费)
  565. 'pay_status' => 20, // 折扣后商品总价(不含运费)
  566. 'transaction_id' => 'PAY' . time() . rand(1000, 9999),
  567. 'discount_point' => $discountPoint,
  568. 'discount_total' => $discountTotal, // 折扣金额
  569. 'delivery_fee' => $deliveryFee, // 运费
  570. 'receiver_name' => $realname,
  571. 'receiver_mobile' => $mobile,
  572. 'receiver_area' => $area,
  573. 'receiver_address' => $address,
  574. 'remark' => '自动复购',
  575. 'create_time' => time(),
  576. 'update_time' => time(),
  577. 'status' => 2,
  578. 'mark' => 1,
  579. ];
  580. // 订单处理
  581. DB::beginTransaction();
  582. if (!$orderId = $this->model->insertGetId($order)) {
  583. DB::rollBack();
  584. $this->error = '创建订单失败';
  585. RedisService::clear($cacheLockKey);
  586. return false;
  587. }
  588. // 订单商品
  589. if ($orderGoods && !OrderGoodsModel::insert($orderGoods)) {
  590. DB::rollBack();
  591. $this->error = '处理订单商品错误';
  592. RedisService::clear($cacheLockKey);
  593. return false;
  594. }
  595. // 创业礼包分单
  596. $data = $order;
  597. $data['total'] = moneyFormat($data['total'] / 6);
  598. $data['bd_score'] = moneyFormat($bdScoreTotal / 6, 2);
  599. $data['profit_total'] = moneyFormat($profitTotal / 6, 2);
  600. $data['pay_total'] = moneyFormat($orderTotal / 6, 2);
  601. $data['pay_money'] = moneyFormat($order['pay_money'] / 6, 2);
  602. $subOrders = [];
  603. for ($i = 1; $i <= 6; $i++) {
  604. $data['order_no'] = get_order_num('BS');
  605. $data['main_no'] = $orderNo;
  606. if ($i == 6) {
  607. $data['total'] = round($order['total'] / 6, 2);
  608. $data['bd_score'] = round($bdScoreTotal / 6, 2);
  609. $data['profit_total'] = round($profitTotal / 6, 2);
  610. $data['pay_total'] = round($orderTotal / 6, 2);
  611. $data['pay_money'] = round($order['pay_money'] / 6, 2);
  612. }
  613. $subOrders[] = $data;
  614. }
  615. //
  616. if ($subOrders && !$this->model->insert($subOrders)) {
  617. DB::rollBack();
  618. $this->error = '处理商品订单失败';
  619. RedisService::clear($cacheLockKey);
  620. return false;
  621. }
  622. // 扣除报单积分
  623. if($bdScoreTotal>0){
  624. if(!MemberModel::where(['id'=>$userId])->update(['bd_score'=>DB::raw("bd_score - {$bdScoreTotal}"),'update_time'=>time()])){
  625. DB::rollBack();
  626. $this->error = '报单积分扣除失败';
  627. RedisService::clear($cacheLockKey);
  628. return false;
  629. }
  630. $data = [
  631. 'user_id'=>$userId,
  632. 'source_order_no'=>$orderNo,
  633. 'user_type'=> 1,
  634. 'account_type'=> 3, // 报单积分
  635. 'type'=> 1,
  636. 'money'=> -$bdScoreTotal,
  637. 'after_money'=>moneyFormat($bdScore - $bdScoreTotal,2),
  638. 'date'=>date('Y-m-d'),
  639. 'create_time'=>time(),
  640. 'remark'=> '创业礼包支付',
  641. 'status'=>1,
  642. 'mark'=>1
  643. ];
  644. if(!AccountLogModel::insertGetId($data)){
  645. Db::rollBack();
  646. $this->error = '付款处理失败';
  647. return false;
  648. }
  649. }
  650. // 余额支付
  651. if(!MemberModel::where(['id'=>$userId])->update(['balance'=>DB::raw("balance - {$payTotal}"),'update_time'=>time()])){
  652. DB::rollBack();
  653. $this->error = '余额支付失败';
  654. RedisService::clear($cacheLockKey);
  655. return false;
  656. }
  657. $data = [
  658. 'user_id'=>$userId,
  659. 'source_order_no'=>$orderNo,
  660. 'user_type'=> 1,
  661. 'account_type'=> 1, // 余额支付
  662. 'type'=> 1,
  663. 'money'=> -$payTotal,
  664. 'after_money'=>moneyFormat($balance - $payTotal,2),
  665. 'date'=>date('Y-m-d'),
  666. 'create_time'=>time(),
  667. 'remark'=> '创业礼包自动复购支付',
  668. 'status'=>1,
  669. 'mark'=>1
  670. ];
  671. if(!AccountLogModel::insertGetId($data)){
  672. Db::rollBack();
  673. $this->error = '自动复购付款处理失败';
  674. return false;
  675. }
  676. // 佣金数据
  677. $order['id'] = $orderId;
  678. if(!$commission = SettleService::make()->commissionCount($order,$orderGoods,$userInfo, $type)){
  679. Db::rollBack();
  680. $this->error = '订单结算处理失败';
  681. return false;
  682. }
  683. // 结算
  684. if(!$settle = SettleService::make()->commissionSettle($orderId)){
  685. Db::rollBack();
  686. $this->error = '订单结算处理失败';
  687. return false;
  688. }
  689. // 用户升级处理
  690. SettleService::make()->updateUserData($userId, $points);
  691. // 用户复购权限恢复
  692. if(!MemberModel::where(['id'=>$userId,'bonus_status'=>1,'update_time'=>time()])){
  693. Db::rollBack();
  694. $this->error = '用户复购处理失败';
  695. return false;
  696. }
  697. // 商品库存扣除
  698. if ($orderGoods) {
  699. foreach ($orderGoods as $item) {
  700. $id = isset($item['goods_id']) ? $item['goods_id'] : 0;
  701. $num = isset($item['num']) ? $item['num'] : 0;
  702. $skuId = isset($item['sku_id']) ? $item['sku_id'] : 0;
  703. if ($id && !GoodsModel::where(['id' => $id])->update(['stock' => DB::raw("stock - {$num}"), 'update_time' => time()])) {
  704. DB::rollBack();
  705. RedisService::clear($cacheLockKey);
  706. $this->error = '商品库存处理失败';
  707. return false;
  708. }
  709. if ($skuId && !GoodsSkuModel::where(['id' => $skuId])->update(['stock' => DB::raw("stock - {$num}"), 'update_time' => time()])) {
  710. DB::rollBack();
  711. RedisService::clear($cacheLockKey);
  712. $this->error = '商品库存处理失败';
  713. return false;
  714. }
  715. }
  716. }
  717. // 用户操作记录
  718. DB::commit();
  719. $this->error = '自动复购成功~';
  720. RedisService::clear($cacheLockKey);
  721. RedisService::clear("caches:orders:settleList");
  722. return [
  723. 'msg'=> '自动复购成功~',
  724. 'order_id' => $orderId,
  725. 'total' => $payTotal,
  726. 'pay_type' => 10,
  727. ];
  728. } catch (\Exception $exception){
  729. $this->error = $exception->getMessage();
  730. return false;
  731. }
  732. }
  733. /**
  734. * 创业大礼包验证
  735. * @param $userId
  736. * @param $goodsId
  737. * @return array|mixed
  738. */
  739. public function checkBusinessOrder($userId, $goodsId)
  740. {
  741. $cacheKey = "caches:orders:check_order:{$userId}_{$goodsId}";
  742. $data = RedisService::get($cacheKey);
  743. if ($data) {
  744. return $data;
  745. }
  746. $data = $this->model->where(['user_id' => $userId, 'meal_id' => $goodsId, 'mark' => 1])
  747. ->where('main_no', '')
  748. ->where('status', '<=', 5)
  749. ->where('refund_status', '<=', 0)
  750. ->count('id');
  751. if ($data) {
  752. RedisService::set($cacheKey, $data, rand(5, 10));
  753. }
  754. return $data;
  755. }
  756. /**
  757. * 订单支付
  758. * @param $userId
  759. * @param $id
  760. * @return array|false
  761. */
  762. public function pay($userId, $id)
  763. {
  764. if ($id <= 0) {
  765. $this->error = '请选择支付订单';
  766. return false;
  767. }
  768. // 缓存锁
  769. $cacheLockKey = "caches:orders:pay_lock:{$userId}_{$id}";
  770. if (RedisService::get($cacheLockKey)) {
  771. $this->error = '订单处理中~';
  772. return false;
  773. }
  774. // 商品数据
  775. RedisService::set($cacheLockKey, ['order_id' => $id, 'user_id' => $userId], rand(3, 5));
  776. // 用户信息
  777. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  778. ->select(['id', 'openid', 'mobile', 'nickname', 'realname', 'balance', 'status'])
  779. ->first();
  780. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  781. $openid = isset($userInfo['openid']) ? $userInfo['openid'] : '';
  782. if (empty($userInfo) || $status != 1) {
  783. $this->error = 1045;
  784. RedisService::clear($cacheLockKey);
  785. return false;
  786. }
  787. if (empty($openid)) {
  788. $this->error = '用户微信未授权,请重新授权登录';
  789. RedisService::clear($cacheLockKey);
  790. return false;
  791. }
  792. // 订单信息
  793. $info = $this->model->where(['id' => $id, 'mark' => 1])
  794. ->select(['id', 'order_no', 'pay_total', 'delivery_fee', 'status'])
  795. ->first();
  796. $orderTotal = isset($info['pay_total']) ? $info['pay_total'] : 0;
  797. $deliveryFee = isset($info['delivery_fee']) ? $info['delivery_fee'] : 0;
  798. $orderNo = isset($info['order_no']) ? $info['order_no'] : '';
  799. $status = isset($info['status']) ? $info['status'] : 0;
  800. if (empty($info) || empty($orderNo)) {
  801. $this->error = '订单信息不存在';
  802. RedisService::clear($cacheLockKey);
  803. return false;
  804. }
  805. if ($status != 1) {
  806. $this->error = '订单已支付';
  807. RedisService::clear($cacheLockKey);
  808. return false;
  809. }
  810. $payTotal = moneyFormat($orderTotal + $deliveryFee);
  811. if (env('PAY_DEBUG')) {
  812. $payTotal = 0.01;
  813. }
  814. // 获取支付参数
  815. /* TODO 支付处理 */
  816. $payOrder = [
  817. 'type' => 1,
  818. 'order_no' => $orderNo,
  819. 'pay_money' => $payTotal,
  820. 'body' => '购物消费',
  821. 'openid' => $openid
  822. ];
  823. // 调起支付
  824. $payment = PaymentService::make()->minPay($userInfo, $payOrder, 'store');
  825. if (empty($payment)) {
  826. DB::rollBack();
  827. RedisService::clear($cacheLockKey);
  828. $this->error = PaymentService::make()->getError();
  829. return false;
  830. }
  831. // 用户操作记录
  832. DB::commit();
  833. $this->error = '支付请求成功,请前往支付~';
  834. RedisService::clear($cacheLockKey);
  835. return [
  836. 'order_id' => $id,
  837. 'payment' => $payment,
  838. 'total' => $payOrder['pay_money'],
  839. 'pay_type' => 10,
  840. ];
  841. }
  842. /**
  843. * 订单取消
  844. * @param $userId
  845. * @param $orderId
  846. * @return array|false
  847. */
  848. public function cancel($userId, $orderId)
  849. {
  850. if ($orderId <= 0) {
  851. $this->error = '请选择订单';
  852. return false;
  853. }
  854. // 缓存锁
  855. $cacheLockKey = "caches:orders:cancel_lock:{$userId}_{$orderId}";
  856. if (RedisService::get($cacheLockKey)) {
  857. $this->error = '订单处理中~';
  858. return false;
  859. }
  860. RedisService::set($cacheLockKey, ['order_id' => $orderId, 'user_id' => $userId], rand(3, 5));
  861. // 用户信息
  862. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  863. ->select(['id', 'openid', 'mobile', 'nickname', 'realname','bd_score', 'balance', 'status'])
  864. ->first();
  865. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  866. $bdScore = isset($userInfo['bd_score']) ? $userInfo['bd_score'] : 0;
  867. if (empty($userInfo) || $status != 1) {
  868. $this->error = 1045;
  869. RedisService::clear($cacheLockKey);
  870. return false;
  871. }
  872. // 订单信息
  873. $info = $this->model->where(['id' => $orderId, 'mark' => 1])
  874. ->select(['id', 'order_no', 'pay_total', 'status'])
  875. ->first();
  876. $orderNo = isset($info['order_no']) ? $info['order_no'] : '';
  877. $status = isset($info['status']) ? $info['status'] : 0;
  878. $bdScoreTotal = isset($info['bd_score']) ? $info['bd_score'] : 0;
  879. if (empty($info) || empty($orderNo)) {
  880. $this->error = '订单信息不存在';
  881. RedisService::clear($cacheLockKey);
  882. return false;
  883. }
  884. if ($status != 1) {
  885. $this->error = '订单已支付';
  886. RedisService::clear($cacheLockKey);
  887. return false;
  888. }
  889. $orderGoods = OrderGoodsModel::where(['order_no' => $orderNo, 'mark' => 1])
  890. ->select(['goods_id', 'num', 'sku_id'])
  891. ->get();
  892. DB::beginTransaction();
  893. if ($orderGoods) {
  894. foreach ($orderGoods as $goods) {
  895. $goodsId = isset($goods['goods_id']) ? $goods['goods_id'] : 0;
  896. $num = isset($goods['num']) ? $goods['num'] : 0;
  897. $skuId = isset($goods['sku_id']) ? $goods['sku_id'] : 0;
  898. if ($goodsId) {
  899. GoodsModel::where(['id' => $goodsId])->update(['stock' => DB::raw("stock + {$num}"), 'update_time' => time()]);
  900. }
  901. if ($skuId) {
  902. GoodsSkuModel::where(['id' => $skuId])->update(['stock' => DB::raw("stock + {$num}"), 'update_time' => time()]);
  903. }
  904. }
  905. }
  906. // 退还报单积分
  907. if($bdScoreTotal>0){
  908. if(!MemberModel::where(['id'=>$userId])->update(['bd_score'=>DB::raw("bd_score + {$bdScoreTotal}"),'update_time'=>time()])){
  909. DB::rollBack();
  910. $this->error = '报单积分退还失败';
  911. RedisService::clear($cacheLockKey);
  912. return false;
  913. }
  914. $data = [
  915. 'user_id'=>$userId,
  916. 'source_order_no'=>$orderNo,
  917. 'user_type'=> 1,
  918. 'account_type'=> 3, // 报单积分
  919. 'type'=> 3,
  920. 'money'=> $bdScoreTotal,
  921. 'after_money'=>moneyFormat($bdScore + $bdScoreTotal,2),
  922. 'date'=>date('Y-m-d'),
  923. 'create_time'=>time(),
  924. 'remark'=> '创业礼包订单取消',
  925. 'status'=>1,
  926. 'mark'=>1
  927. ];
  928. if(!AccountLogModel::insertGetId($data)){
  929. Db::rollBack();
  930. $this->error = '订单取消处理失败';
  931. return false;
  932. }
  933. }
  934. $this->error = '取消订单成功';
  935. $this->model->where(['user_id' => $userId, 'mark' => 0])->where('update_time', '<=', time() - 300)->delete();
  936. OrderGoodsModel::where(['order_no' => $orderNo, 'mark' => 0])->where('update_time', '<=', time() - 300)->delete();
  937. $this->model->where(['id' => $orderId])->update(['mark' => 0, 'update_time' => time()]);
  938. OrderGoodsModel::where(['order_no' => $orderNo])->update(['mark' => 0, 'update_time' => time()]);
  939. DB::commit();
  940. return ['id' => $orderId];
  941. }
  942. /**
  943. * 订单删除隐藏
  944. * @param $userId
  945. * @param $orderId
  946. * @return array|false
  947. */
  948. public function hide($userId, $orderId)
  949. {
  950. if ($orderId <= 0) {
  951. $this->error = '请选择订单';
  952. return false;
  953. }
  954. // 缓存锁
  955. $cacheLockKey = "caches:orders:hide_lock:{$userId}_{$orderId}";
  956. if (RedisService::get($cacheLockKey)) {
  957. $this->error = '订单删除中~';
  958. return false;
  959. }
  960. RedisService::set($cacheLockKey, ['order_id' => $orderId, 'user_id' => $userId], rand(3, 5));
  961. // 用户信息
  962. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  963. ->select(['id', 'openid', 'mobile', 'nickname', 'realname', 'balance', 'status'])
  964. ->first();
  965. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  966. if (empty($userInfo) || $status != 1) {
  967. $this->error = 1045;
  968. RedisService::clear($cacheLockKey);
  969. return false;
  970. }
  971. // 订单信息
  972. $info = $this->model->where(['id' => $orderId, 'mark' => 1])
  973. ->select(['id', 'order_no', 'pay_total', 'status'])
  974. ->first();
  975. $orderNo = isset($info['order_no']) ? $info['order_no'] : '';
  976. $status = isset($info['status']) ? $info['status'] : 0;
  977. if (empty($info) || empty($orderNo)) {
  978. $this->error = '订单信息不存在';
  979. RedisService::clear($cacheLockKey);
  980. return false;
  981. }
  982. if ($status != 4) {
  983. $this->error = '订单未完成';
  984. RedisService::clear($cacheLockKey);
  985. return false;
  986. }
  987. $this->error = '删除订单成功';
  988. $this->model->where(['id' => $orderId])->update(['is_hide' => 1, 'update_time' => time()]);
  989. return ['id' => $orderId];
  990. }
  991. /**
  992. * 订单完成
  993. * @param $userId 订单用户ID
  994. * @param $id 订单ID
  995. * @return array|false
  996. */
  997. public function complete($userId, $id, $check = true)
  998. {
  999. if ($id <= 0) {
  1000. $this->error = '请选择订单';
  1001. return false;
  1002. }
  1003. // 缓存锁
  1004. $cacheLockKey = "caches:orders:complete_lock:{$userId}_{$id}";
  1005. if (RedisService::get($cacheLockKey)) {
  1006. $this->error = '订单处理中~';
  1007. return false;
  1008. }
  1009. // 商品数据
  1010. RedisService::set($cacheLockKey, ['order_id' => $id, 'user_id' => $userId], rand(3, 5));
  1011. // 用户信息
  1012. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  1013. ->select(['id', 'openid', 'mobile', 'parent_id', 'nickname', 'realname', 'balance', 'status'])
  1014. ->first();
  1015. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  1016. $parentId = isset($userInfo['parent_id']) ? $userInfo['parent_id'] : 0;
  1017. if ($check && (empty($userInfo) || $status != 1)) {
  1018. $this->error = 1045;
  1019. RedisService::clear($cacheLockKey);
  1020. return false;
  1021. }
  1022. // 订单信息
  1023. $info = $this->model->with(['orderGoods','commission'])->where(['id' => $id, 'mark' => 1])
  1024. ->select(['id', 'order_no','type', 'user_id', 'store_id', 'total', 'pay_total', 'delivery_no', 'delivery_company', 'delivery_code', 'status'])
  1025. ->first();
  1026. $orderNo = isset($info['order_no']) ? $info['order_no'] : '';
  1027. $deliveryNo = isset($info['delivery_no']) ? $info['delivery_no'] : '';
  1028. $deliverCompany = isset($info['delivery_company']) ? $info['delivery_company'] : '';
  1029. $orderUserId = isset($info['user_id']) ? $info['user_id'] : 0;
  1030. $storeId = isset($info['store_id']) ? $info['store_id'] : 0;
  1031. $orderType = isset($info['type']) ? $info['type'] : 0;
  1032. $orderTotal = isset($info['total']) ? $info['total'] : 0;
  1033. $status = isset($info['status']) ? $info['status'] : 0;
  1034. $commission = isset($info['commission']) ? $info['commission'] : [];
  1035. $bonus = isset($commission['bonus'])?$commission['bonus'] : 0;
  1036. $orderGoods = isset($info['order_goods']) ? $info['order_goods'] : [];
  1037. if (empty($info) || empty($orderNo)) {
  1038. $this->error = '订单信息不存在';
  1039. RedisService::clear($cacheLockKey);
  1040. return false;
  1041. }
  1042. if ($status != 3) {
  1043. $this->error = '订单未发货';
  1044. RedisService::clear($cacheLockKey);
  1045. return false;
  1046. }
  1047. if (empty($deliveryNo) || empty($deliverCompany)) {
  1048. $this->error = '订单发货信息错误,请联系客服';
  1049. $this->model->where(['id' => $id])->update(['is_complete' => 1, 'complete_remark' => $this->error]);
  1050. RedisService::clear("caches:orders:completeList");
  1051. RedisService::clear($cacheLockKey);
  1052. return false;
  1053. }
  1054. DB::beginTransaction();
  1055. $completeStatus = env('ORDER_COMPLETE_STATUS', 5);
  1056. $updateData = ['status' => $completeStatus, 'complete_at' => date('Y-m-d H:i:s'), 'update_time' => time()];
  1057. if (!$check) {
  1058. $updateData['is_complete'] = 1;
  1059. $updateData['complete_remark'] = '自动收货';
  1060. }
  1061. $this->model->where(['id' => $id])->update($updateData);
  1062. // 商家订单数据统计
  1063. $updateData = ['order_count' => DB::raw('order_count+1'), 'order_total' => DB::raw("order_total + {$orderTotal}")];
  1064. StoreModel::where(['id' => $storeId])->update($updateData);
  1065. // 商品销量数据
  1066. if ($orderGoods) {
  1067. $counts = [];
  1068. foreach ($orderGoods as $item) {
  1069. $counts[$item['goods_id']] = isset($counts[$item['goods_id']]) ? $counts[$item['goods_id']] : 0;
  1070. $counts[$item['goods_id']] += $item['num'];
  1071. }
  1072. if ($counts) {
  1073. foreach ($counts as $id => $v) {
  1074. GoodsModel::where(['id' => $id])->update(['sales' => DB::raw("sales + {$v}"), 'update_time' => time()]);
  1075. }
  1076. }
  1077. }
  1078. // 商城订单结算
  1079. if($orderType == 1){
  1080. SettleService::make()->commissionSettle($id);
  1081. }
  1082. DB::commit();
  1083. $this->error = '确认收货成功';
  1084. RedisService::clear("caches:orders:completeList");
  1085. return ['id' => $id, 'msg' => $this->error];
  1086. }
  1087. /**
  1088. * 售后或退款
  1089. * @param $userId
  1090. * @param $params
  1091. * @return array|false
  1092. */
  1093. public function after($userId, $params)
  1094. {
  1095. $id = isset($params['id']) ? $params['id'] : 0;
  1096. $afterType = isset($params['after_type']) ? $params['after_type'] : 1;
  1097. if ($id <= 0) {
  1098. $this->error = '请选择订单';
  1099. return false;
  1100. }
  1101. // 缓存锁
  1102. $cacheLockKey = "caches:orders:after_lock:{$userId}_{$id}";
  1103. if (RedisService::get($cacheLockKey)) {
  1104. $this->error = '订单处理中~';
  1105. return false;
  1106. }
  1107. // 商品数据
  1108. RedisService::set($cacheLockKey, ['params' => $params, 'user_id' => $userId], rand(3, 5));
  1109. // 用户信息
  1110. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  1111. ->select(['id', 'openid', 'mobile', 'nickname', 'realname', 'balance', 'status'])
  1112. ->first();
  1113. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  1114. if (empty($userInfo) || $status != 1) {
  1115. $this->error = 1045;
  1116. RedisService::clear($cacheLockKey);
  1117. return false;
  1118. }
  1119. // 订单信息
  1120. $info = $this->model->where(['id' => $id, 'mark' => 1])
  1121. ->select(['id', 'order_no', 'after_type', 'refund_status', 'pay_total', 'status'])
  1122. ->first();
  1123. $orderNo = isset($info['order_no']) ? $info['order_no'] : '';
  1124. $status = isset($info['status']) ? $info['status'] : 0;
  1125. $refundStatus = isset($info['refund_status']) ? $info['refund_status'] : 0;
  1126. if (empty($info) || empty($orderNo)) {
  1127. $this->error = '订单信息不存在';
  1128. RedisService::clear($cacheLockKey);
  1129. return false;
  1130. }
  1131. if ($status == 1) {
  1132. $this->error = '订单未支付';
  1133. RedisService::clear($cacheLockKey);
  1134. return false;
  1135. }
  1136. if ($status == 4 && $afterType == 2) {
  1137. $this->error = '订单已完成';
  1138. RedisService::clear($cacheLockKey);
  1139. return false;
  1140. }
  1141. if ($refundStatus > 0 && $refundStatus != 4) {
  1142. $this->error = '订单售后处理中';
  1143. RedisService::clear($cacheLockKey);
  1144. return false;
  1145. }
  1146. $afterRealname = isset($params['after_realname']) ? $params['after_realname'] : '';
  1147. $afterPhone = isset($params['after_phone']) ? $params['after_phone'] : '';
  1148. $afterRemark = isset($params['after_remark']) ? $params['after_remark'] : '';
  1149. if ($afterType == 1) {
  1150. if (empty($afterRealname) || empty($afterPhone) || empty($afterRemark)) {
  1151. $this->error = '请填写售后信息';
  1152. RedisService::clear($cacheLockKey);
  1153. return false;
  1154. }
  1155. }
  1156. $data = [
  1157. 'after_type' => $afterType,
  1158. 'after_realname' => $afterRealname,
  1159. 'after_phone' => $afterPhone,
  1160. 'after_remark' => $afterRemark,
  1161. 'refund_remark' => isset($params['refund_remark']) ? $params['refund_remark'] : '',
  1162. 'refund_status' => 3,
  1163. 'update_time' => time()
  1164. ];
  1165. $this->model->where(['id' => $id])->update($data);
  1166. $this->error = '订单申请售后成功';
  1167. return ['id' => $id];
  1168. }
  1169. /**
  1170. * 物流查询
  1171. * @param $id
  1172. * @return array|false|mixed
  1173. */
  1174. public function getDelivery($id)
  1175. {
  1176. $info = $this->model->where(['id' => $id, 'mark' => 1])->first();
  1177. $deliveryNo = isset($info['delivery_no']) ? $info['delivery_no'] : '';
  1178. $deliveryCode = isset($info['delivery_code']) ? $info['delivery_code'] : '';
  1179. $mobile = isset($info['receiver_mobile']) ? $info['receiver_mobile'] : '';
  1180. $receiverArea = isset($info['receiver_area']) && $info['receiver_area'] ? $info['receiver_area'] : '';
  1181. if (empty($info)) {
  1182. $this->error = '请选择订单';
  1183. return false;
  1184. }
  1185. $cacheKey = "caches:kd100:order_{$id}";
  1186. $data = RedisService::get($cacheKey);
  1187. if ($data) {
  1188. return $data;
  1189. }
  1190. $result = Kd100Service::make()->query($deliveryNo, $mobile, $deliveryCode, $receiverArea);
  1191. RedisService::set($cacheKey . '_result', $result, 300);
  1192. $status = isset($result['status']) ? $result['status'] : 0;
  1193. $data = isset($result['data']) ? $result['data'] : [];
  1194. $courierInfo = isset($result['courierInfo']) ? $result['courierInfo'] : [];
  1195. $arrivalTime = isset($result['arrivalTime']) ? $result['arrivalTime'] : '';
  1196. $predictedRoute = isset($result['predictedRoute']) ? $result['predictedRoute'] : [];
  1197. $predictedData = $predictedRoute ? end($predictedRoute) : [];
  1198. $arrivalData = [];
  1199. if ($arrivalTime) {
  1200. $arrivalData['arrivalTime'] = dayFormat(strtotime($arrivalTime . ':00:00'));
  1201. $arrivalData['predictedData'] = $predictedData;
  1202. }
  1203. if ($courierInfo && $courierInfo['deliveryManPhone']) {
  1204. $courierInfo['deliveryManPhone'] = explode(',', $courierInfo['deliveryManPhone']);
  1205. $courierInfo['deliveryPhone'] = $courierInfo['deliveryManPhone'][1] ? $courierInfo['deliveryManPhone'][1] : $courierInfo['deliveryManPhone'][0];
  1206. }
  1207. if ($data && $status == 200) {
  1208. RedisService::set($cacheKey, ['info' => $courierInfo, 'arrivalData' => $arrivalData, 'list' => $data], 1200);
  1209. }
  1210. return $data ? ['info' => $courierInfo, 'arrivalData' => $arrivalData, 'list' => $data] : [];
  1211. }
  1212. /**
  1213. * 已发货待完成订单
  1214. * @return array|mixed
  1215. */
  1216. public function getCompleteOrders()
  1217. {
  1218. $cacheKey = "caches:orders:completeList";
  1219. $datas = RedisService::get($cacheKey);
  1220. if ($datas) {
  1221. return $datas;
  1222. }
  1223. $completeDay = ConfigService::make()->getConfigByCode('order_complete_day', 7);
  1224. $limitNum = ConfigService::make()->getConfigByCode('order_complete_batch_num', 300);
  1225. $limitNum = $limitNum > 10 && $limitNum < 2000 ? $limitNum : 300;
  1226. $completeDay = $completeDay >= 1 && $completeDay < 30 ? $completeDay : 7;
  1227. $datas = $this->model->where(['status' => 3, 'is_complete' => 2, 'mark' => 1])
  1228. ->whereNotNull('delivery_no')
  1229. ->select(['id', 'user_id', 'order_no', 'status'])
  1230. ->where('pay_at', '<=', date('Y-m-d H:i:s', time() - $completeDay * 86400))
  1231. ->limit($limitNum)
  1232. ->get();
  1233. $datas = $datas ? $datas->toArray() : [];
  1234. if ($datas) {
  1235. RedisService::set($cacheKey, $datas, rand(300, 600));
  1236. }
  1237. return $datas;
  1238. }
  1239. /**
  1240. * 待结算订单
  1241. * @return array|mixed
  1242. */
  1243. public function getSettleOrders()
  1244. {
  1245. $cacheKey = "caches:orders:settleList";
  1246. $datas = RedisService::get($cacheKey);
  1247. if ($datas) {
  1248. return $datas;
  1249. }
  1250. $limitNum = ConfigService::make()->getConfigByCode('order_settle_batch_num', 500);
  1251. $limitNum = $limitNum > 10 && $limitNum < 2000 ? $limitNum : 300;
  1252. $datas = $this->model->from('orders as a')
  1253. ->leftJoin('orders_commissions as b','b.order_id','=','a.id')
  1254. ->where(['a.status' => 2,'a.refund_status'=>0, 'b.status'=>2, 'a.mark' => 1])
  1255. ->select(['a.id', 'a.user_id', 'a.order_no', 'a.status'])
  1256. ->limit($limitNum)
  1257. ->get();
  1258. $datas = $datas ? $datas->toArray() : [];
  1259. if ($datas) {
  1260. RedisService::set($cacheKey, $datas, rand(300, 600));
  1261. }
  1262. return $datas;
  1263. }
  1264. /**
  1265. * 已完成,待分账订单
  1266. * @return array|mixed
  1267. */
  1268. public function getRevenueOrderList()
  1269. {
  1270. $cacheKey = "caches:orders:revenueList";
  1271. $datas = RedisService::get($cacheKey);
  1272. if ($datas) {
  1273. return $datas;
  1274. }
  1275. $limitNum = ConfigService::make()->getConfigByCode('order_revenue_batch_num', 300);
  1276. $limitNum = $limitNum > 10 && $limitNum < 2000 ? $limitNum : 300;
  1277. $datas = $this->model->where(['status' => 4, 'is_revenue' => 1, 'revenue_status' => 2, 'mark' => 1])
  1278. ->select(['id', 'user_id', 'pay_total', 'order_no', 'revenue_no', 'transaction_id', 'status'])
  1279. ->limit($limitNum)
  1280. ->get();
  1281. $datas = $datas ? $datas->toArray() : [];
  1282. if ($datas) {
  1283. RedisService::set($cacheKey, $datas, rand(300, 600));
  1284. }
  1285. return $datas;
  1286. }
  1287. /**
  1288. * 订单分账处理
  1289. * @param $id
  1290. * @return false
  1291. * @throws \Yansongda\Pay\Exception\ContainerException
  1292. * @throws \Yansongda\Pay\Exception\InvalidParamsException
  1293. */
  1294. public function revenue($id)
  1295. {
  1296. if ($id <= 0) {
  1297. $this->error = '订单参数错误';
  1298. return false;
  1299. }
  1300. // 缓存锁
  1301. $cacheLockKey = "caches:orders:revenue_lock:{$id}";
  1302. if (RedisService::get($cacheLockKey)) {
  1303. $this->error = '订单分账处理中~';
  1304. return false;
  1305. }
  1306. // 是否设置分账账户
  1307. $revenueOpenid = ConfigService::make()->getConfigByCode('order_revenue_openid', '');
  1308. if (empty($revenueOpenid)) {
  1309. $this->error = '订单分账账户未配置';
  1310. return false;
  1311. }
  1312. // 订单信息
  1313. RedisService::set($cacheLockKey, ['id' => $id, 'date' => date('Y-m-d H:i:s')], 20);
  1314. $info = $this->model->where(['id' => $id, 'mark' => 1])
  1315. ->select(['id', 'order_no', 'revenue_no', 'user_id', 'transaction_id', 'pay_total', 'is_revenue', 'revenue_status', 'revenue_amount', 'status'])
  1316. ->first();
  1317. $revenueOrderNo = isset($info['revenue_no']) ? $info['revenue_no'] : '';
  1318. $revenueAmount = isset($info['revenue_amount']) ? $info['revenue_amount'] : 0;
  1319. $status = isset($info['status']) ? $info['status'] : 0;
  1320. $isRevenue = isset($info['is_revenue']) ? $info['is_revenue'] : 0;
  1321. $revenueStatus = isset($info['revenue_status']) ? $info['revenue_status'] : 0;
  1322. if ($status != 4) {
  1323. RedisService::clear($cacheLockKey);
  1324. $this->error = '订单状态错误,未完成收货的订单无法分账';
  1325. return false;
  1326. }
  1327. if ($isRevenue != 1) {
  1328. RedisService::clear($cacheLockKey);
  1329. $this->error = '该订单不是分账订单';
  1330. return false;
  1331. }
  1332. if ($revenueStatus != 2) {
  1333. RedisService::clear($cacheLockKey);
  1334. $this->error = '该订单分账已处理完成';
  1335. return false;
  1336. }
  1337. if ($revenueAmount <= 0) {
  1338. RedisService::clear($cacheLockKey);
  1339. $this->error = '订单分账金额不足';
  1340. return false;
  1341. }
  1342. $order = [
  1343. 'transaction_id' => $info['transaction_id'],
  1344. 'out_order_no' => $revenueOrderNo,
  1345. 'body' => '订单分账',
  1346. 'amount' => $revenueAmount,
  1347. 'unsplit' => true, // 只分一次
  1348. ];
  1349. $result = PaymentService::make()->profitsharing($revenueOpenid, $order);
  1350. $state = isset($result->state) ? $result->state : 0;
  1351. $message = isset($result->message) ? $result->message : '分账失败';
  1352. $orderId = isset($result->order_id) ? $result->order_id : '';
  1353. if ($state == 'FINISHED') {
  1354. $this->model->where(['id' => $id])->update(['revenue_status' => 1, 'revenue_order_id' => $orderId, 'update_time' => time()]);
  1355. RedisService::clear($cacheLockKey);
  1356. RedisService::clear("caches:orders:revenueList");
  1357. $this->error = '分账处理成功';
  1358. return true;
  1359. } else {
  1360. RedisService::clear($cacheLockKey);
  1361. $this->error = $message;
  1362. return false;
  1363. }
  1364. }
  1365. }