OrderService.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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\Common;
  12. use App\Models\AccountLogModel;
  13. use App\Models\ActionLogModel;
  14. use App\Models\GoodsModel;
  15. use App\Models\MemberModel;
  16. use App\Models\MessageModel;
  17. use App\Models\OrderModel;
  18. use App\Services\BaseService;
  19. use App\Services\RedisService;
  20. use Illuminate\Support\Facades\DB;
  21. /**
  22. * 订单管理-服务类
  23. * @author laravel开发员
  24. * @since 2020/11/11
  25. * Class OrderService
  26. * @package App\Services\Common
  27. */
  28. class OrderService extends BaseService
  29. {
  30. // 静态对象
  31. protected static $instance = null;
  32. /**
  33. * 构造函数
  34. * @author laravel开发员
  35. * @since 2020/11/11
  36. * OrderService constructor.
  37. */
  38. public function __construct()
  39. {
  40. $this->model = new OrderModel();
  41. }
  42. /**
  43. * 静态入口
  44. * @return static|null
  45. */
  46. public static function make()
  47. {
  48. if (!self::$instance) {
  49. self::$instance = (new static());
  50. }
  51. return self::$instance;
  52. }
  53. /**
  54. * @param $params
  55. * @param int $pageSize
  56. * @return array
  57. */
  58. public function getDataList($params, $pageSize = 15)
  59. {
  60. $query = $this->getQuery($params);
  61. $countModel = clone $query;
  62. $countModel1 = clone $query;
  63. $status = isset($params['status']) ? $params['status'] : 0;
  64. if($status==0){
  65. $counts = [
  66. 'status2'=> $countModel->where('a.status',2)->count('a.id'),
  67. 'status3'=> $countModel1->where('a.status',3)->count('a.id'),
  68. ];
  69. }else {
  70. $counts = [];
  71. }
  72. $list = $query->select(['a.*'])
  73. ->orderBy('a.status', 'asc')
  74. ->orderBy('a.create_time', 'desc')
  75. ->orderBy('a.id', 'desc')
  76. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  77. $list = $list ? $list->toArray() : [];
  78. if ($list) {
  79. foreach ($list['data'] as &$item) {
  80. $item['create_time'] = $item['create_time'] ? datetime($item['create_time'], 'Y-m-d H:i:s') : '';
  81. $item['goods'] = isset($item['goods'])? $item['goods'] : [];
  82. $item['user'] = isset($item['user'])? $item['user'] : [];
  83. if($item['goods']){
  84. $item['goods']['shipper_city'] = isset($item['goods']['shipper_city'])? $item['goods']['shipper_city'] : [];
  85. $item['goods']['shipper_district'] = isset($item['goods']['shipper_district'])? $item['goods']['shipper_district'] : [];
  86. $city = [];
  87. if(isset($item['goods']['shipper_city']['name']) && $item['goods']['shipper_city']['name']){
  88. $city[] = $item['goods']['shipper_city']['name'];
  89. }
  90. if(isset($item['goods']['shipper_district']['name']) && $item['goods']['shipper_district']['name']){
  91. $city[] = $item['goods']['shipper_district']['name'];
  92. }
  93. $item['goods']['shipper_area'] = ($city? implode(' ', $city) :'');
  94. $item['goods']['receiver_city'] = isset($item['goods']['receiver_city'])? $item['goods']['receiver_city'] : [];
  95. $item['goods']['receiver_district'] = isset($item['goods']['receiver_district'])? $item['goods']['receiver_district'] : [];
  96. $city = [];
  97. if(isset($item['goods']['receiver_city']['name']) && $item['goods']['receiver_city']['name']){
  98. $city[] = $item['goods']['receiver_city']['name'];
  99. }
  100. if(isset($item['goods']['receiver_district']['name']) && $item['goods']['receiver_district']['name']){
  101. $city[] = $item['goods']['receiver_district']['name'];
  102. }
  103. $item['goods']['receiver_area'] = ($city? implode(' ', $city) :'');
  104. }
  105. }
  106. // 消息已读
  107. if($status>0){
  108. MessageModel::where(['is_read'=>2,'type'=>5,'mark'=>1])->update(['is_read'=>1,'update_time'=>time()]);
  109. }
  110. }
  111. return [
  112. 'pageSize' => $pageSize,
  113. 'total' => isset($counts['count']) ? $counts['count'] : 0,
  114. 'counts' => $counts,
  115. 'list' => isset($list['data']) ? $list['data'] : []
  116. ];
  117. }
  118. /**
  119. * 查询
  120. * @param $params
  121. * @return \Illuminate\Database\Eloquent\Builder
  122. */
  123. public function getQuery($params)
  124. {
  125. $where = ['a.mark' => 1];
  126. $userId = isset($params['user_id']) ? $params['user_id'] : 0;
  127. return $this->model->with(['user','goods'])->from('orders as a')
  128. ->leftJoin('member as b', 'a.user_id', '=', 'b.id')
  129. ->leftJoin('goods as c', 'c.id', '=', 'a.goods_id')
  130. ->where($where)
  131. ->where(function ($query) use ($params) {
  132. $keyword = isset($params['keyword']) ? $params['keyword'] : '';
  133. if ($keyword) {
  134. $query->where('a.order_no', 'like', "%{$keyword}%");
  135. }
  136. // 接单人
  137. $account = isset($params['account']) ? $params['account'] : '';
  138. if ($account) {
  139. $query->where(function($query) use($account){
  140. $query->where('b.nickname', 'like', "%{$account}%")->orWhere('b.mobile', 'like', "%{$account}%");
  141. });
  142. }
  143. // 商品
  144. $goodsId = isset($params['goods_id']) ? intval($params['goods_id']) : 0;
  145. $goods = isset($params['goods']) ? trim($params['goods']) : '';
  146. if ($goods) {
  147. $query->where(function($query) use($goods){
  148. $query->where('c.goods_name', 'like', "%{$goods}%");
  149. if(preg_match("/^(1[0-9]+|[1-9]+)$/", $goods)){
  150. $query->where('a.goods_id', intval($goods));
  151. }else{
  152. $query->where('c.goods_name', 'like', "%{$goods}%");
  153. }
  154. });
  155. }
  156. if($goodsId>0){
  157. $query->where('a.goods_id', intval($goodsId));
  158. }
  159. })
  160. ->where(function ($query) use ($params) {
  161. $status = isset($params['status']) ? $params['status'] : 0;
  162. if($status==0){
  163. $query->whereIn('a.status',[2,3]);
  164. }else if($status){
  165. $query->where('a.status', $status);
  166. }
  167. })
  168. ->where(function ($query) use ($userId) {
  169. if($userId){
  170. $query->where('a.user_id', '=', $userId);
  171. }
  172. });
  173. }
  174. /**
  175. * 按日期统计订单数
  176. * @param string $beginAt 开始时间
  177. * @param string $endAt 结束时间
  178. * @param int[] $status 状态:数组或数值
  179. * @return mixed
  180. */
  181. public function getCountByTime($beginAt='', $endAt='', $status=3)
  182. {
  183. $cacheKey = "caches:orders:count_{$status}_{$beginAt}_{$endAt}";
  184. $data = RedisService::get($cacheKey);
  185. if($data){
  186. return $data;
  187. }
  188. $where = ['mark' => 1];
  189. $data = $this->model->where($where)->where(function($query) use($beginAt,$endAt,$status){
  190. if($beginAt && $endAt){
  191. $query->whereBetween('create_time', [strtotime($beginAt), strtotime($endAt)]);
  192. }else if($beginAt){
  193. $query->where('create_time','>=', strtotime($beginAt));
  194. }
  195. if($status && is_array($status)){
  196. $query->whereIn('status',$status);
  197. }else if($status){
  198. $query->where('status',$status);
  199. }
  200. })->count('id');
  201. if($data){
  202. RedisService::set($cacheKey, $data, rand(300, 600));
  203. }
  204. return $data;
  205. }
  206. /**
  207. * 按日期统计订单金额
  208. * @param string $beginAt 开始时间
  209. * @param string $endAt 结束时间
  210. * @param int[] $status 状态:数组或数值
  211. * @return mixed
  212. */
  213. public function getTotalByTime($beginAt='', $endAt='', $status=3)
  214. {
  215. $cacheKey = "caches:orders:total_{$status}_{$beginAt}_{$endAt}";
  216. $data = RedisService::get($cacheKey);
  217. if($data){
  218. return $data;
  219. }
  220. $where = ['mark' => 1];
  221. $data = $this->model->where($where)->where(function($query) use($beginAt,$endAt,$status){
  222. if($beginAt && $endAt){
  223. $query->whereBetween('create_time', [strtotime($beginAt), strtotime($endAt)]);
  224. }else if($beginAt){
  225. $query->where('create_time','>=', strtotime($beginAt));
  226. }
  227. if($status && is_array($status)){
  228. $query->whereIn('status',$status);
  229. }else if($status){
  230. $query->where('status',$status);
  231. }
  232. })->sum('total');
  233. if($data){
  234. RedisService::set($cacheKey, $data, rand(300, 600));
  235. }
  236. return $data;
  237. }
  238. /**
  239. * 添加或编辑
  240. * @return array
  241. * @since 2020/11/11
  242. * @author laravel开发员
  243. */
  244. public function edit()
  245. {
  246. $params = request()->post();
  247. return parent::edit($params); // TODO: Change the autogenerated stub
  248. }
  249. /**
  250. * 订单审核
  251. * @return bool
  252. */
  253. public function confirm($adminId, $params)
  254. {
  255. $id = isset($params['id'])? intval($params['id']) : 0;
  256. $remark = isset($params['remark'])? trim($params['remark']) : '';
  257. $info = $this->model->with(['user','goods'])->where(['id'=> $id,'mark'=>1])->first();
  258. $userInfo = isset($info['user'])? $info['user'] : [];
  259. $goods = isset($info['goods'])? $info['goods'] : [];
  260. $status = isset($info['status'])? $info['status'] : 0;
  261. $orderUserId = isset($info['user_id'])? $info['user_id'] : 0;
  262. $goodsId = isset($info['goods_id'])? $info['goods_id'] : 0;
  263. if(empty($info) || empty($goods) || empty($userInfo) || $goodsId<=0 || $orderUserId<=0){
  264. $this->error = '订单信息不存在或参数错误';
  265. return false;
  266. }
  267. if($status != 1){
  268. $this->error = '订单状态不可操作';
  269. return false;
  270. }
  271. if($this->model->where(['goods_id'=> $goodsId,'status'=>3,'mark'=>1])->value('id')){
  272. $this->error = '该货物订单已完成';
  273. return false;
  274. }
  275. if($this->model->where(['goods_id'=> $goodsId,'status'=>2,'mark'=>1])->value('id')){
  276. $this->error = '该货物存在订单进行中';
  277. return false;
  278. }
  279. DB::beginTransaction();
  280. if(!$this->model->where(['id'=> $id])->update(['status'=>2,'confirm_admin_id'=>$adminId,'confirm_at'=>date('Y-m-d H:i:s'),'remark'=> $remark,'update_time'=>time()])){
  281. DB::rollBack();
  282. $this->error = '订单审核失败';
  283. return false;
  284. }
  285. $this->model->where(['goods_id'=> $goodsId,'status'=> 1])->whereNotIn('id',[$id])->update(['status'=>4,'confirm_admin_id'=>$adminId,'confirm_at'=>date('Y-m-d H:i:s'),'remark'=> '订单无效','update_time'=>time()]);
  286. if(!MemberModel::where(['id'=>$orderUserId])->update(['picker_order_num'=>DB::raw("picker_order_num + 1"),'update_time'=>time()])){
  287. DB::rollBack();
  288. $this->error = '订单审核失败';
  289. return false;
  290. }
  291. if(!GoodsModel::where(['id'=>$goodsId])->update(['picker_status'=>2,'update_time'=>time()])){
  292. DB::rollBack();
  293. $this->error = '订单审核失败';
  294. return false;
  295. }
  296. DB::commit();
  297. $this->error = '订单审核成功';
  298. return ['id'=> $id];
  299. }
  300. /**
  301. * 订单取消
  302. * @return bool
  303. */
  304. public function cancel($adminId, $params)
  305. {
  306. $id = isset($params['id'])? intval($params['id']) : 0;
  307. $remark = isset($params['remark'])? trim($params['remark']) : '';
  308. $info = $this->model->with(['user','goods'])->where(['id'=> $id,'mark'=>1])->first();
  309. $userInfo = isset($info['user'])? $info['user'] : [];
  310. $goods = isset($info['goods'])? $info['goods'] : [];
  311. $status = isset($info['status'])? $info['status'] : 0;
  312. $orderUserId = isset($info['user_id'])? $info['user_id'] : 0;
  313. $goodsId = isset($info['goods_id'])? $info['goods_id'] : 0;
  314. if(empty($info) || empty($goods) || empty($userInfo) || $goodsId<=0 || $orderUserId<=0){
  315. $this->error = '订单信息不存在或参数错误';
  316. return false;
  317. }
  318. if($status ==4){
  319. $this->error = '订单已完成';
  320. return false;
  321. }
  322. DB::beginTransaction();
  323. if(!$this->model->where(['id'=> $id])->update(['status'=>4,'confirm_admin_id'=>$adminId,'confirm_at'=>date('Y-m-d H:i:s'),'remark'=> $remark,'update_time'=>time()])){
  324. DB::rollBack();
  325. $this->error = '订单取消失败';
  326. return false;
  327. }
  328. $pickerOrderNum = isset($userInfo['picker_order_num'])? $userInfo['picker_order_num'] : 0;
  329. if(!MemberModel::where(['id'=>$orderUserId])->update(['picker_order_num'=>$pickerOrderNum?DB::raw("picker_order_num - 1"): 0,'update_time'=>time()])){
  330. DB::rollBack();
  331. $this->error = '订单取消失败';
  332. return false;
  333. }
  334. if(!GoodsModel::where(['id'=>$goodsId])->update(['picker_status'=>1,'update_time'=>time()])){
  335. DB::rollBack();
  336. $this->error = '订单取消失败';
  337. return false;
  338. }
  339. DB::commit();
  340. $this->error = '订单取消成功';
  341. return ['id'=> $id];
  342. }
  343. /**
  344. * 订单完成
  345. * @return bool
  346. */
  347. public function complete($adminId, $params)
  348. {
  349. $id = isset($params['id'])? intval($params['id']) : 0;
  350. $remark = isset($params['remark'])? trim($params['remark']) : '';
  351. $info = $this->model->with(['user','goods'])->where(['id'=> $id,'mark'=>1])->first();
  352. $userInfo = isset($info['user'])? $info['user'] : [];
  353. $goods = isset($info['goods'])? $info['goods'] : [];
  354. $status = isset($info['status'])? $info['status'] : 0;
  355. $orderUserId = isset($info['user_id'])? $info['user_id'] : 0;
  356. $goodsId = isset($info['goods_id'])? $info['goods_id'] : 0;
  357. $bonus = isset($info['bonus'])? $info['bonus'] : 0;
  358. if(empty($info) || empty($goods) || empty($userInfo) || $goodsId<=0 || $orderUserId<=0){
  359. $this->error = '订单信息不存在或参数错误';
  360. return false;
  361. }
  362. if($status != 2){
  363. $this->error = '订单状态不可操作';
  364. return false;
  365. }
  366. DB::beginTransaction();
  367. if(!$this->model->where(['id'=> $id])->update(['status'=>3,'confirm_admin_id'=>$adminId,'confirm_at'=>date('Y-m-d H:i:s'),'remark'=> $remark,'update_time'=>time()])){
  368. DB::rollBack();
  369. $this->error = '订单确认完成失败';
  370. return false;
  371. }
  372. // 收入结算
  373. if($bonus>0){
  374. $updateData = [
  375. 'balance'=>DB::raw("balance + {$bonus}"),
  376. 'income_total'=>DB::raw("income_total + {$bonus}"),
  377. 'complete_order_num'=>DB::raw("complete_order_num + 1"),
  378. 'update_time'=>time()
  379. ];
  380. if(!MemberModel::where(['id'=>$orderUserId])->update($updateData)){
  381. DB::rollBack();
  382. $this->error = '订单确认完成收入结算失败';
  383. return false;
  384. }
  385. // 收入记录
  386. $balance = isset($userInfo['balance'])? $userInfo['balance'] : 0;
  387. $log = [
  388. 'user_id' => $orderUserId,
  389. 'source_order_no' => isset($info['order_no']) ? $info['order_no'] : '',
  390. 'type' => 1,
  391. 'money' => $bonus,
  392. 'before_money' => $balance,
  393. 'date'=> date('Y-m-d'),
  394. 'create_time' => time(),
  395. 'remark' => '订单收入',
  396. 'status' => 1,
  397. 'mark' => 1,
  398. ];
  399. if(!AccountLogModel::insertGetId($log)){
  400. DB::rollBack();
  401. $this->error = '订单确认完成收入结算失败';
  402. return false;
  403. }
  404. }
  405. if(!GoodsModel::where(['id'=>$goodsId])->update(['picker_status'=>3,'update_time'=>time()])){
  406. DB::rollBack();
  407. $this->error = '订单确认完成失败';
  408. return false;
  409. }
  410. DB::commit();
  411. $this->error = '订单确认完成成功';
  412. return ['id'=> $id];
  413. }
  414. /**
  415. * 删除
  416. * @return array
  417. */
  418. public function delete()
  419. {
  420. // 设置日志标题
  421. ActionLogModel::setRecord(session('userId'), ['type' => 1, 'title' => "删除订单信息", 'content' => json_encode(request()->post(), 256), 'module' => 'admin']);
  422. ActionLogModel::record();
  423. $this->model->where('mark', 0)->where('update_time', '<=', time() - 7 * 86400)->delete();
  424. return parent::delete(); // TODO: Change the autogenerated stub
  425. }
  426. }