OrderService.php 59 KB

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