User.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 https://www.thinkphp.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: thinkphp <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\api\model;
  13. use app\api\validate\user\Info as ValidateInfo;
  14. use app\common\model\UnlockOrder;
  15. use app\common\model\UnlockUser;
  16. use think\facade\Cache;
  17. use app\api\service\User as UserService;
  18. use app\api\model\UserOauth as UserOauthModel;
  19. use app\common\model\User as UserModel;
  20. use cores\exception\BaseException;
  21. use yiovo\captcha\facade\CaptchaApi;
  22. /**
  23. * 用户模型类
  24. * Class User
  25. * @package app\api\model
  26. */
  27. class User extends UserModel
  28. {
  29. /**
  30. * 隐藏字段
  31. * @var array
  32. */
  33. protected $hidden = [
  34. 'open_id',
  35. 'is_delete',
  36. 'store_id',
  37. 'create_time',
  38. 'update_time'
  39. ];
  40. /**
  41. * 获取列表
  42. * @param array $param 查询条件
  43. * @param int $listRows 分页数量
  44. * @return mixed|\think\model\Collection|\think\Paginator
  45. * @throws \think\db\exception\DbException
  46. */
  47. public function getList(array $param = [], int $listRows = 15)
  48. {
  49. // 整理查询参数
  50. $params = array_merge($param, ['status' => 1, 'is_delete' => 0]);
  51. // 获取列表
  52. $list = parent::getList($params, $listRows);
  53. if ($list->isEmpty()) {
  54. return $list;
  55. }
  56. // 整理列表数据并返回
  57. return $this->setListDataFromApi($list);
  58. }
  59. /**
  60. * 获取生源学校用户列表
  61. * @param array $param 查询条件
  62. * @param int $listRows 分页数量
  63. * @return mixed|\think\model\Collection|\think\Paginator
  64. * @throws \think\db\exception\DbException
  65. */
  66. public function getSourceSchoolUserList(array $param = [], int $listRows = 15)
  67. {
  68. // 整理查询参数
  69. $params = array_merge($param, ['status' => 1, 'is_delete' => 0, 'ui.status' => 1, 'user_type' => 1]);
  70. // 获取商品列表
  71. $list = parent::getList($params, $listRows);
  72. if ($list->isEmpty()) {
  73. return $list;
  74. }
  75. // 整理列表数据并返回
  76. return $this->setListDataFromApi($list, $params);
  77. }
  78. /**
  79. * 设置展示的数据 api模块
  80. * @param $info
  81. * @return mixed
  82. */
  83. private function setListDataFromApi($list, $params = [])
  84. {
  85. // 是否验证和统计解锁用户
  86. $checkType = isset($params['check_type']) ? $params['check_type'] : 0;
  87. $userId = isset($params['user_id']) ? $params['user_id'] : 0;
  88. $schoolId = isset($params['school_id']) ? $params['school_id'] : 0;
  89. $list = $this->setListData($list, function ($data) use ($checkType, $userId, $schoolId) {
  90. $data['avatar'] = isset($data['avatar']) ? $data['avatar'] : [];
  91. unset($data['avatar']);
  92. $data['is_locked'] = 2;
  93. // 是否验证已被解锁
  94. if ($checkType == 1) {
  95. $data['is_locked'] = (int)UnlockUser::checkUserByUser($data['user_id'], $userId, $schoolId);
  96. }
  97. // 整理数据 api模块
  98. $this->setDataFromApi($data);
  99. // 隐藏冗余的字段
  100. $hidden = ['user_type', 'user_login', 'home_bg', 'update_time', 'grade_id', 'platform', 'status', 'country', 'province', 'city', 'address', 'address_id', 'balance', 'points', 'last_login_time', 'pay_money', 'expend_money', 'last_login_time'];
  101. $this->hidden(array_merge($this->hidden, $hidden));
  102. });
  103. $list = $list ? $list->toArray() : [];
  104. if ($checkType == 1 && $userId > 0 && isset($list['total'])) {
  105. $list['locked_num'] = (int)UnlockUser::getCountByUser($userId, $schoolId);
  106. $list['lock_num'] = max(0, $list['total'] - $list['locked_num']);
  107. }
  108. asort($list);
  109. return $list;
  110. }
  111. /**
  112. * 整理数据 api模块
  113. * @param $info
  114. * @return mixed
  115. */
  116. private function setDataFromApi($info)
  117. {
  118. return $this->setData($info, function ($data) {
  119. $data['region_name'] = $data['region_id'] ? Region::getNameById($data['region_id']) : '';
  120. // 粉丝数
  121. $data['fans_num'] = $data['user_id'] ? UserFans::getFansNum($data['user_id']) : 0;
  122. });
  123. }
  124. /**
  125. * 获取器:隐藏手机号中间四位
  126. * @param string $value
  127. * @return string
  128. */
  129. public function getMobileAttr(string $value): string
  130. {
  131. return strlen($value) === 11 ? hide_mobile($value) : $value;
  132. }
  133. /**
  134. * 获取主页背景
  135. * @param string $value
  136. * @return string
  137. */
  138. public function getHomeBgAttr(string $value): string
  139. {
  140. return $value? getPreview($value) :'';
  141. }
  142. /**
  143. * 获取用户信息
  144. * @param string $token
  145. * @return User|array|false|null
  146. * @throws BaseException
  147. */
  148. public static function getUserByToken(string $token)
  149. {
  150. // 检查登录态是否存在
  151. if (!Cache::has($token)) {
  152. return false;
  153. }
  154. // 用户的ID
  155. $userId = (int)Cache::get($token)['user']['user_id'];
  156. // 用户基本信息
  157. $userInfo = self::detail($userId);
  158. $userInfo['info'] = $userInfo['info'] ? $userInfo['info'] : [];
  159. if ($userInfo['info']) {
  160. if($userInfo['user_type'] == 3){
  161. $userInfo['info']['school'] = isset($userInfo['info']['school']) && $userInfo['info']['school'] ? $userInfo['info']['school'] : [];
  162. }else{
  163. $userInfo['info']['school'] = isset($userInfo['info']['sourceSchool']) && $userInfo['info']['sourceSchool'] ? $userInfo['info']['sourceSchool'] : [];
  164. unset($userInfo['info']['sourceSchool']);
  165. }
  166. }
  167. if (empty($userInfo) || $userInfo['is_delete']) {
  168. throwError('很抱歉,用户信息不存在或已删除', config('status.not_logged'));
  169. }
  170. if ($userInfo['status'] != 1) {
  171. throwError('很抱歉,用户账号已被冻结', config('status.not_logged'));
  172. }
  173. // 获取用户关联的第三方用户信息(当前客户端)
  174. try {
  175. if (getPlatform() && getPlatform() != 'MP-WEIXIN') {
  176. $userInfo['currentOauth'] = UserOauthModel::getOauth($userId, getPlatform());
  177. }
  178. } catch (\Throwable $e) {
  179. throwError($e->getMessage());
  180. }
  181. return $userInfo;
  182. }
  183. /**
  184. * 绑定手机号(当前登录用户)
  185. * @param array $data
  186. * @return bool
  187. * @throws BaseException
  188. */
  189. public function bindMobile(array $data): bool
  190. {
  191. // 当前登录的用户信息
  192. $userInfo = UserService::getCurrentLoginUser(true);
  193. // 验证绑定的手机号
  194. $this->checkBindMobile($data);
  195. // 更新手机号记录
  196. return $userInfo->save(['mobile' => $data['mobile']]);
  197. }
  198. /**
  199. * 设置用户头像和背景图片
  200. * @param array $data
  201. * @return bool
  202. * @throws BaseException
  203. */
  204. public function setImage(array $data): bool
  205. {
  206. // 当前登录的用户信息
  207. $userInfo = UserService::getCurrentLoginUser(true);
  208. //var_dump($userInfo);
  209. $type = isset($data['type'])? intval($data['type']) : 0;
  210. if($type == 1){
  211. $avatarId = isset($data['file_id'])? intval($data['file_id']) : 0;
  212. if($avatarId<=0){
  213. throwError('请先上传头像');
  214. }
  215. return $userInfo->save(['avatar_id'=> $avatarId]);
  216. }else if($type == 2){
  217. $filePath = isset($data['file_path'])? $data['file_path'] : '';
  218. if(empty($filePath)){
  219. throwError('请先上传背景图片');
  220. }
  221. return $userInfo->save(['home_bg'=> $filePath]);
  222. }
  223. return false;
  224. }
  225. /**
  226. * 验证绑定的手机号
  227. * @param array $data
  228. * @return void
  229. * @throws BaseException
  230. */
  231. private function checkBindMobile(array $data): void
  232. {
  233. // 验证短信验证码是否匹配
  234. if (!CaptchaApi::checkSms($data['smsCode'], $data['mobile'])) {
  235. throwError('短信验证码不正确');
  236. }
  237. // 判断手机号是否已存在
  238. if (static::checkExistByMobile($data['mobile'])) {
  239. throwError('很抱歉,该手机号已绑定其他账户');
  240. }
  241. }
  242. /**
  243. * @param array $data
  244. * @return string
  245. * @throws BaseException
  246. */
  247. public function saveInfo(array $data): string
  248. {
  249. // 修改手机号需要验证验证码
  250. $userInfo = UserService::getCurrentLoginUser(true);
  251. // 验证信息
  252. $this->checkInfo($data, $userInfo);
  253. $info = UserInfo::detail($userInfo['user_id']);
  254. if (!is_null($info) && $info['school_id'] && $info['school_id'] != $data['school_id']) {
  255. throwError('已认证注册,无法修改学校,请联系客服');
  256. }
  257. if ((!is_null($info) && $info['school_id']) && $userInfo['user_type'] && $data['user_type'] != $userInfo['user_type']) {
  258. throwError('账号类型不可修改');
  259. }
  260. $userInfo->transaction(function () use ($data, $userInfo, $info) {
  261. try {
  262. $userData = [
  263. 'user_id' => $userInfo['user_id'],
  264. 'real_name' => $data['real_name'],
  265. 'gender' => (int)$data['gender'],
  266. 'age' => isset($data['age']) ? intval($data['age']) : 0,
  267. 'student_no' => isset($data['student_no']) ? $data['student_no'] : '',
  268. 'user_login' => isset($data['user_login']) ? $data['user_login'] : '',
  269. 'mobile' => $data['mobile'],
  270. ];
  271. if ($userInfo['user_type'] <= 0 || (is_null($info) || $info['school_id'] <= 0)) {
  272. $userData['user_type'] = (int)$data['user_type'];
  273. }
  274. $userInfo->save($userData);
  275. $infoData = [
  276. 'user_id' => $userInfo['user_id'],
  277. 'school_id' => (int)$data['school_id'],
  278. 'position' => isset($data['position']) ? intval($data['position']) : 0,
  279. 'speciality' => isset($data['speciality']) ? intval($data['speciality']) : 0,
  280. 'qq' => isset($data['qq']) ? $data['qq'] : '',
  281. 'idcard' => isset($data['idcard']) ? $data['idcard'] : '',
  282. 'idcard_front_img' => isset($data['idcard_front_img']) ? $data['idcard_front_img'] : '',
  283. 'work_certify' => isset($data['work_certify']) ? $data['work_certify'] : '',
  284. 'education_certify' => isset($data['education_certify']) ? $data['education_certify'] : '',
  285. 'parent_name' => isset($data['parent_name']) ? $data['parent_name'] : '',
  286. 'admission_year' => isset($data['admission_year']) ? $data['admission_year'] : '',
  287. 'status' => $data['user_type'] != 3 ? 1 : (isset($info['status']) ? $info['status'] : 2),
  288. ];
  289. // 资料是否被修改过
  290. if ($this->checkModifyInfo($data, $info)) {
  291. $infoData['status'] = 2;
  292. }
  293. if (is_null($info)) {
  294. (new UserInfo)->save($infoData);
  295. } else {
  296. $info->save($infoData);
  297. }
  298. // 更新生源学校生源数量
  299. $model = new SourceShool();
  300. $model->setInc(['source_shools_id' => (int)$data['school_id']], 'students_num', 1);
  301. } catch (\Exception $exception) {
  302. throwError('保存失败');
  303. }
  304. });
  305. return $info || $data['user_type'] != 3 ? '保存成功' : '保存成功,等待审核';
  306. }
  307. /**
  308. * 验证重要资料是否已修改
  309. * @param array $data
  310. * @param $info
  311. * @return bool
  312. */
  313. public function checkModifyInfo(array $data, $info): bool
  314. {
  315. if ($data['user_type'] != 3) {
  316. return false;
  317. }
  318. if (is_null($info)) {
  319. return true;
  320. }
  321. $checkFields = ['idcard', 'mobile', 'real_name', 'user_login', 'student_no'];
  322. foreach ($checkFields as $field) {
  323. if (isset($data[$field]) && $info[$field] != $data[$field]) {
  324. return true;
  325. }
  326. }
  327. return false;
  328. }
  329. /**
  330. * 验证用户信息
  331. * @param array $data
  332. * @param array $userInfo
  333. * @return bool
  334. * @throws BaseException
  335. */
  336. private function checkInfo(array $data, UserModel $userInfo): void
  337. {
  338. $validate = new ValidateInfo;
  339. if (!$validate->check($data)) {
  340. throwError($validate->getError());
  341. }
  342. if ($data['user_type'] == 2 && empty($data['parent_name'])) {
  343. throwError('家长姓名不为空');
  344. }
  345. if (empty($data['school_id'])) {
  346. throwError('学校不为空');
  347. }
  348. if ($data['user_type'] == 1) {
  349. /*if(empty($data['admission_year'])){
  350. throwError('请选择入学年份');
  351. }
  352. if(empty($data['education_certify'])){
  353. throwError('请上传教育证明');
  354. }*/
  355. } else if ($data['user_type'] == 3) {
  356. if (empty($data['position'])) {
  357. throwError('请选择职务');
  358. }
  359. /*if(empty($data['work_certify'])){
  360. throwError('请上传职务证明');
  361. }*/
  362. }
  363. if ($userInfo['mobile'] != $data['mobile']) {
  364. if (empty($data['smsCode'])) {
  365. throwError('短信验证码不为空');
  366. }
  367. // 验证短信验证码是否匹配
  368. if ($data['smsCode'] && ($data['smsCode'] != '123456' && !CaptchaApi::checkSms($data['smsCode'], $data['mobile']))) {
  369. throwError('短信验证码不正确');
  370. }
  371. }
  372. $checkId = UserInfo::checkExistByIdcard($data['idcard']);
  373. if ($data['idcard'] && $checkId && $userInfo['user_id'] != $checkId) {
  374. throwError('身份证号码已被使用');
  375. }
  376. /*if(empty($data['idcard_front_img'])){
  377. throwError('请上传身份证明');
  378. }*/
  379. $chekId = self::checkExistByMobile($data['mobile']);
  380. if ($data['mobile'] && $chekId && $userInfo['user_id'] != $chekId) {
  381. throwError('手机号码已被使用');
  382. }
  383. }
  384. /**
  385. * 获取生源学校下的所有生源用户ID
  386. * @param $sourceSchoolId
  387. * @return mixed
  388. */
  389. public static function getSourceUserIds($sourceSchoolId, $ids = [])
  390. {
  391. return self::alias('u')
  392. ->leftJoin('user_info ui', 'ui.user_id=u.user_id')
  393. ->where(['ui.school_id' => $sourceSchoolId, 'u.user_type' => 1, 'u.is_delete' => 0, 'u.status' => 1, 'ui.status' => 1])
  394. ->whereNotIn('u.user_id', $ids)
  395. ->column('u.user_id');
  396. }
  397. }