MemberService.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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\Helpers\Jwt;
  13. use App\Models\ActionLogModel;
  14. use App\Models\MemberModel;
  15. use App\Models\ShopModel;
  16. use App\Services\BaseService;
  17. use App\Services\RedisService;
  18. use phpQrcode\QRcode;
  19. /**
  20. * 会员管理-服务类
  21. * @author laravel开发员
  22. * @since 2020/11/11
  23. * Class MemberService
  24. * @package App\Services\Common
  25. */
  26. class MemberService extends BaseService
  27. {
  28. // 静态对象
  29. protected static $instance = null;
  30. /**
  31. * 构造函数
  32. * @author laravel开发员
  33. * @since 2020/11/11
  34. * MemberService constructor.
  35. */
  36. public function __construct()
  37. {
  38. $this->model = new MemberModel();
  39. }
  40. /**
  41. * 静态入口
  42. * @return static|null
  43. */
  44. public static function make()
  45. {
  46. if (!self::$instance) {
  47. self::$instance = (new static());
  48. }
  49. return self::$instance;
  50. }
  51. /**
  52. * 获取资料详情
  53. * @param $where
  54. * @param array $field
  55. */
  56. public function getInfo($where, array $field = [])
  57. {
  58. $field = $field ? $field : ['id', 'username', 'realname','mobile', 'nickname','login_shop_id','code','parent_id', 'openid','score_rate', 'idcard', 'idcard_check', 'idcard_front_img', 'idcard_back_img', 'member_level', 'bonus','bonus_total','score', 'status', 'avatar'];
  59. if (is_array($where)) {
  60. $info = $this->model->where($where)->select($field)->first();
  61. } else {
  62. $info = $this->model->where(['id' => (int)$where])->select($field)->first();
  63. }
  64. $info = $info ? $info->toArray() : [];
  65. if ($info) {
  66. $info['avatar'] = $info['avatar'] ? get_image_url($info['avatar']) : '';
  67. $info['bonus'] = round($info['bonus'],0);
  68. $info['mobile'] = $info['mobile']? format_mobile($info['mobile']):'';
  69. $info['show_bonus'] = GoodsService::make()->checkNewGoods($info['id']);
  70. // 二维码
  71. $qrcode = $this->makeQrcode(env('WEB_URL').'h5/#/pages/register/index?code='.$info['code']);
  72. $info['qrcode'] = $qrcode? get_image_url($qrcode):'';
  73. $info['shop_info'] = [];
  74. if(isset($info['login_shop_id']) && $info['login_shop_id']){
  75. $info['shop_info'] = ShopService::make()->getInfo($info['login_shop_id']);
  76. }
  77. // 交易订单统计
  78. $info['orderCounts'] = TradeService::make()->getNewTradeCountByStatus($info['id'],[1,2,3]);
  79. // 积分订单统计
  80. $info['scoreOrderCount'] = OrderService::make()->getNewTradeCount($info['id'],[1,2,3,4,5]);
  81. }
  82. return $info;
  83. }
  84. /**
  85. * 用户登录
  86. * @param $params
  87. * @return array|false
  88. */
  89. public function login($params)
  90. {
  91. $mobile = isset($params['mobile']) ? $params['mobile'] : '';
  92. $password = isset($params['password']) ? $params['password'] : '';
  93. $shopCode = isset($params['shop_code']) ? $params['shop_code'] : '';
  94. if (empty($mobile) || empty($password)) {
  95. $this->error = 2009;
  96. return false;
  97. }
  98. if(empty($shopCode)){
  99. $this->error = 2010;
  100. return false;
  101. }
  102. // 验证店铺
  103. if(!$shopId = ShopModel::where(['code'=> $shopCode,'status'=>1,'mark'=>1])->value('id')){
  104. $this->error = 2011;
  105. return false;
  106. }
  107. // 用户验证
  108. $info = $this->model->getOne([['mobile', '=', $mobile]]);
  109. if (!$info) {
  110. $this->error = 2001;
  111. return false;
  112. }
  113. // 密码校验
  114. $password = get_password($password . md5($password . env('APP_NAME')));
  115. if ($password != $info['password']) {
  116. $this->error = 2002;
  117. return false;
  118. }
  119. // 使用状态校验
  120. if ($info['status'] != 1) {
  121. $this->error = 2012;
  122. return false;
  123. }
  124. // 设置日志标题
  125. ActionLogModel::setTitle("会员登录");
  126. ActionLogModel::record($info);
  127. // JWT生成token
  128. $jwt = new Jwt('jwt_app');
  129. $token = $jwt->getToken($info['id']);
  130. RedisService::set("stores:auths:info:{$info['id']}", $info, 5, 10);
  131. // 登录
  132. $updateData = ['login_time' => time(),'login_shop_id'=> $shopId,'login_count'=>$info['login_count']+1, 'login_ip' => get_client_ip()];
  133. $this->model->where(['id' => $info['id']])->update($updateData);
  134. // 登录数据
  135. return [
  136. 'token' => $token,
  137. 'user_id' => $info['id'],
  138. 'shop_id' => $shopId,
  139. ];
  140. }
  141. /**
  142. * 用户注册
  143. * @param $params
  144. * @return bool
  145. */
  146. public function register($params)
  147. {
  148. // 检测账号是否存在
  149. if ($this->checkExists('mobile', $params['mobile'])) {
  150. $this->error = '2005';
  151. return false;
  152. }
  153. $mobile = isset($params['mobile']) ? trim($params['mobile']) : '';
  154. $nickname = isset($params['nickname']) ? trim($params['nickname']) : '';
  155. $password = isset($params['password']) ? trim($params['password']) : '';
  156. $safePassword = isset($params['safe_password']) ? trim($params['safe_password']) : '';
  157. $inviteCode = isset($params['invite_code']) ? trim($params['invite_code']) : '';
  158. $inviteInfo = $this->model->where(['code'=> $inviteCode,'mark'=>1])->select(['id','code','username','parents'])->first();
  159. if(empty($inviteInfo)){
  160. $this->error = '2013';
  161. return false;
  162. }
  163. $parentId = isset($inviteInfo['id'])? $inviteInfo['id'] : 0;
  164. $parents = isset($inviteInfo['parents'])? $inviteInfo['parents'] : '';
  165. $parents = $parents? rtrim($parents,',').",{$parentId}," : "{$parentId},";
  166. $data = [
  167. 'nickname' => $nickname,
  168. 'username' => strtoupper('U'.get_random_code(7)),
  169. 'password' => get_password($password . md5($password . env('APP_NAME'))),
  170. 'safe_password' => get_password($safePassword . md5($safePassword . env('APP_NAME'))),
  171. 'mobile' => $mobile,
  172. 'parents' => $parents,
  173. 'parent_id' => $parentId,
  174. 'status' => 1,
  175. 'mark' => 1,
  176. 'create_time' => time(),
  177. ];
  178. if ($id = $this->model->edit($data)) {
  179. $this->model->where(['id'=> $id])->update(['code'=> strtoupper('Q'.get_random_code(8))]);
  180. $this->error = 2008;
  181. return true;
  182. }
  183. $this->error = 2007;
  184. return false;
  185. }
  186. /**
  187. * @param $params
  188. * @param int $pageSize
  189. * @return array
  190. */
  191. public function getDataList($params, $pageSize = 15)
  192. {
  193. $where = ['a.mark' => 1];
  194. $status = isset($params['status'])? $params['status'] : 0;
  195. $parentId = isset($params['parent_id'])? $params['parent_id'] : 0;
  196. if($parentId>0){
  197. $where['a.parent_id'] = $parentId;
  198. }
  199. if($status>0){
  200. $where['a.status'] = $status;
  201. }
  202. $list = $this->model->from('member as a')
  203. ->leftJoin('shop as b', 'b.user_id', '=', 'a.id')
  204. ->leftJoin('member as c', 'c.id', '=', 'a.parent_id')
  205. ->where($where)
  206. ->where(function ($query) use($params){
  207. $keyword = isset($params['keyword'])? $params['keyword'] : '';
  208. if($keyword){
  209. $query->where('a.username','like',"%{$keyword}%")->orWhere('a.mobile','like',"%{$keyword}%");
  210. }
  211. })
  212. ->select(['a.*','b.id as shop_id','b.name as shop_name','c.code as parent_code','c.nickname as parent_name'])
  213. ->orderBy('a.create_time','desc')
  214. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  215. $list = $list? $list->toArray() :[];
  216. if($list){
  217. foreach($list['data'] as &$item){
  218. $item['create_time'] = $item['create_time']? datetime($item['create_time'],'Y-m-d H.i.s') : '';
  219. $item['login_time'] = $item['login_time']? datetime($item['login_time'],'Y-m-d H.i.s') : '';
  220. $item['avatar'] = isset($item['avatar']) && $item['avatar']? get_image_url($item['avatar']) : '';
  221. $item['parent_code'] = isset($item['parent_code']) && $item['parent_code']? $item['parent_code'] : '无';
  222. $item['invite_num'] = MemberService::make()->getInviteNums($item['id']);
  223. }
  224. }
  225. return [
  226. 'pageSize'=> $pageSize,
  227. 'total'=>isset($list['total'])? $list['total'] : 0,
  228. 'list'=> isset($list['data'])? $list['data'] : []
  229. ];
  230. }
  231. /**
  232. * 直推用户数
  233. * @param $userId
  234. * @return array|mixed
  235. */
  236. public function getInviteNums($userId)
  237. {
  238. $cacheKey = "caches:member:inviteNums";
  239. $data = RedisService::get($cacheKey);
  240. if($data){
  241. return $data;
  242. }
  243. $data = $this->model->where(['parent_id'=> $userId, 'mark'=> 1])->count('id');
  244. if($data){
  245. RedisService::set($cacheKey, $data, rand(3, 5));
  246. }
  247. return $data;
  248. }
  249. /**
  250. * 上级用户列表
  251. * @return array
  252. */
  253. public function parents()
  254. {
  255. // 获取参数
  256. $param = request()->all();
  257. // 用户ID
  258. $keyword = getter($param, "keyword");
  259. $parentId = getter($param, "parent_id");
  260. $userId = getter($param, "user_id");
  261. $datas = $this->model->where(function($query) use($parentId){
  262. if($parentId){
  263. $query->where(['id'=> $parentId,'mark'=>1]);
  264. }else{
  265. $query->where(['status'=> 1,'mark'=>1]);
  266. }
  267. })
  268. ->where(function($query) use($userId){
  269. if($userId){
  270. $query->whereNotIn('id', [$userId]);
  271. }
  272. })
  273. ->where(function($query) use($keyword){
  274. if($keyword){
  275. $query->where('username','like',"{$keyword}%")->orWhere('mobile','like',"{$keyword}%");
  276. }
  277. })
  278. ->select(['id','username','code','nickname','status'])
  279. ->get();
  280. return $datas? $datas->toArray() : [];
  281. }
  282. /**
  283. * 生成普通参数二维码
  284. * @param $str 参数
  285. * @param bool $refresh 是否重新生成
  286. * @return bool
  287. */
  288. public function makeQrcode($str, $refresh = false, $size = 4, $margin = 2, $level = 2)
  289. {
  290. $qrFile = '/images/qrcode/';
  291. if (!is_dir('/uploads' . $qrFile)) {
  292. @mkdir('./uploads' . $qrFile, 0755, true);
  293. }
  294. $qrFile = $qrFile . 'C_' . strtoupper(md5($str . '_' . $size . $margin . $level)) . '.png';
  295. $cacheKey = "caches:qrcodes:member_" . md5($str);
  296. if (RedisService::get($cacheKey) && is_file('/uploads' . $qrFile) && !$refresh) {
  297. //return $qrFile;
  298. }
  299. QRcode::png($str, './uploads' . $qrFile, $level, $size, $margin);
  300. if (!file_exists('./uploads' . $qrFile)) {
  301. return false;
  302. }
  303. RedisService::set($cacheKey, ['str' => $str, 'qrcode' => $qrFile, 'date' => date('Y-m-d H:i:s')], 7 * 24 * 3600);
  304. return $qrFile;
  305. }
  306. /**
  307. * 推荐树
  308. * @return array|false|mixed
  309. */
  310. public function getTree()
  311. {
  312. // 请求参数
  313. $keyword = request()->post('keyword','');
  314. $cacheKey = "caches:member:trees:".md5('t'.$keyword);
  315. $datas = RedisService::get($cacheKey);
  316. if($datas){
  317. return $datas;
  318. }
  319. $datas = $this->model->where(['status'=>1,'mark'=>1])
  320. ->select(['id','username','nickname','mobile','parent_id','status'])
  321. ->get()->keyBy('id');
  322. $datas = $datas? $datas->toArray() : [];
  323. $pid = 0;
  324. if($keyword){
  325. $data = $this->model->where(function($query) use($keyword){
  326. $query->where('nickname','like',"{$keyword}%")->orWhere('mobile','like',"{$keyword}%");
  327. })
  328. ->where(['status'=>1,'mark'=>1])
  329. ->orderBy('parent_id','asc')
  330. ->select(['id','parent_id','nickname','mobile','username'])
  331. ->first();
  332. $nickname = isset($data['nickname'])? $data['nickname'] : '';
  333. $username = isset($data['username'])? $data['username'] : '';
  334. $mobile = isset($data['mobile'])? $data['mobile'] : '';
  335. if($data){
  336. $pid = isset($data['id'])? $data['id'] : 0;
  337. $data['label'] = $nickname.($mobile?"({$mobile})":"");
  338. unset($data['nickname']);
  339. unset($data['username']);
  340. }
  341. }
  342. $datas = get_tree($datas, $pid);
  343. if($datas){
  344. if($pid){
  345. $data['children'] = $datas;
  346. $newDatas[0] = $data;
  347. $datas = $newDatas;
  348. }
  349. RedisService::set($cacheKey, $datas, rand(3,5));
  350. }
  351. return $datas;
  352. }
  353. /**
  354. * 添加会编辑会员
  355. * @return array
  356. * @since 2020/11/11
  357. * @author laravel开发员
  358. */
  359. public function edit()
  360. {
  361. // 请求参数
  362. $data = request()->all();
  363. // 头像处理
  364. $avatar = isset($data['avatar'])? trim($data['avatar']) : '';
  365. if ($avatar && strpos($avatar, "temp")) {
  366. $data['avatar'] = save_image($avatar, 'member');
  367. } else if($avatar){
  368. $data['avatar'] = str_replace(IMG_URL, "", $data['avatar']);
  369. }
  370. return parent::edit($data); // TODO: Change the autogenerated stub
  371. }
  372. /**
  373. * 重置密码
  374. * @return array
  375. * @since 2020/11/14
  376. * @author laravel开发员
  377. */
  378. public function resetPwd()
  379. {
  380. // 获取参数
  381. $param = request()->all();
  382. // 用户ID
  383. $userId = getter($param, "id");
  384. if (!$userId) {
  385. return message("用户ID不能为空", false);
  386. }
  387. $userInfo = $this->model->getInfo($userId);
  388. if (!$userInfo) {
  389. return message("用户信息不存在", false);
  390. }
  391. // 设置新密码
  392. $password = '123456';
  393. $userInfo['password'] = get_password($password . md5($password.env('APP_NAME')));
  394. $result = $this->model->edit($userInfo);
  395. if (!$result) {
  396. return message("重置密码失败", false);
  397. }
  398. return message("重置密码成功");
  399. }
  400. /**
  401. * 修改账号
  402. * @param $userId
  403. * @param $params
  404. * @return bool
  405. */
  406. public function modify($userId, $params)
  407. {
  408. $username = isset($params['username']) ? $params['username'] : '';
  409. $newUsername = isset($params['new_username']) ? $params['new_username'] : '';
  410. $password = isset($params['password']) ? $params['password'] : '';
  411. if (empty($username) || empty($password)) {
  412. $this->error = 1013;
  413. return false;
  414. }
  415. // 用户验证
  416. $info = $this->model->getOne([['username', '=', $username]]);
  417. if (!$info || $info['id'] != $userId) {
  418. $this->error = 2001;
  419. return false;
  420. }
  421. // 使用状态校验
  422. if ($info['status'] != 1) {
  423. $this->error = 2009;
  424. return false;
  425. }
  426. // 密码校验
  427. $password = get_password($password . md5($password . 'otc'));
  428. if ($password != $info['password']) {
  429. $this->error = 2002;
  430. return false;
  431. }
  432. $checkInfo = $this->model->getOne([['username', '=', $newUsername]]);
  433. if ($checkInfo && $checkInfo['id'] != $info['id']) {
  434. $this->error = 2005;
  435. return false;
  436. }
  437. if (!$this->model->where(['id' => $info['id']])->update(['username' => $newUsername, 'update_time' => time()])) {
  438. $this->error = 2021;
  439. return false;
  440. }
  441. $this->error = 2020;
  442. return true;
  443. }
  444. /**
  445. * 修改更新登录密码
  446. * @param $userId
  447. * @param $params
  448. * @return bool
  449. */
  450. public function updatePassword($userId, $params)
  451. {
  452. $username = isset($params['username']) ? $params['username'] : '';
  453. $password = isset($params['password']) ? $params['password'] : '';
  454. if (empty($username) || empty($password)) {
  455. $this->error = 1013;
  456. return false;
  457. }
  458. // 用户验证
  459. $info = $this->model->getOne([['username', '=', $username]]);
  460. if (!$info || $info['id'] != $userId) {
  461. $this->error = 2001;
  462. return false;
  463. }
  464. // 使用状态校验
  465. if ($info['status'] != 1) {
  466. $this->error = 2009;
  467. return false;
  468. }
  469. // 更新登录密码
  470. $password = get_password($password . md5($password . 'otc'));
  471. if (!$this->model->where(['id' => $info['id']])->update(['password' => $password, 'update_time' => time()])) {
  472. $this->error = 2025;
  473. return false;
  474. }
  475. $this->error = 2024;
  476. return true;
  477. }
  478. }