User.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. $userInfo['info']['school'] = isset($userInfo['info']['school']) && $userInfo['info']['school'] ? $userInfo['info']['school'] : [];
  161. }
  162. if (empty($userInfo) || $userInfo['is_delete']) {
  163. throwError('很抱歉,用户信息不存在或已删除', config('status.not_logged'));
  164. }
  165. if ($userInfo['status'] != 1) {
  166. throwError('很抱歉,用户账号已被冻结', config('status.not_logged'));
  167. }
  168. // 获取用户关联的第三方用户信息(当前客户端)
  169. try {
  170. if (getPlatform() && getPlatform() != 'MP-WEIXIN') {
  171. $userInfo['currentOauth'] = UserOauthModel::getOauth($userId, getPlatform());
  172. }
  173. } catch (\Throwable $e) {
  174. throwError($e->getMessage());
  175. }
  176. return $userInfo;
  177. }
  178. /**
  179. * 绑定手机号(当前登录用户)
  180. * @param array $data
  181. * @return bool
  182. * @throws BaseException
  183. */
  184. public function bindMobile(array $data): bool
  185. {
  186. // 当前登录的用户信息
  187. $userInfo = UserService::getCurrentLoginUser(true);
  188. // 验证绑定的手机号
  189. $this->checkBindMobile($data);
  190. // 更新手机号记录
  191. return $userInfo->save(['mobile' => $data['mobile']]);
  192. }
  193. /**
  194. * 设置用户头像和背景图片
  195. * @param array $data
  196. * @return bool
  197. * @throws BaseException
  198. */
  199. public function setImage(array $data): bool
  200. {
  201. // 当前登录的用户信息
  202. $userInfo = UserService::getCurrentLoginUser(true);
  203. //var_dump($userInfo);
  204. $type = isset($data['type'])? intval($data['type']) : 0;
  205. if($type == 1){
  206. $avatarId = isset($data['file_id'])? intval($data['file_id']) : 0;
  207. if($avatarId<=0){
  208. throwError('请先上传头像');
  209. }
  210. return $userInfo->save(['avatar_id'=> $avatarId]);
  211. }else if($type == 2){
  212. $filePath = isset($data['file_path'])? $data['file_path'] : '';
  213. if(empty($filePath)){
  214. throwError('请先上传背景图片');
  215. }
  216. return $userInfo->save(['home_bg'=> $filePath]);
  217. }
  218. return false;
  219. }
  220. /**
  221. * 验证绑定的手机号
  222. * @param array $data
  223. * @return void
  224. * @throws BaseException
  225. */
  226. private function checkBindMobile(array $data): void
  227. {
  228. // 验证短信验证码是否匹配
  229. if (!CaptchaApi::checkSms($data['smsCode'], $data['mobile'])) {
  230. throwError('短信验证码不正确');
  231. }
  232. // 判断手机号是否已存在
  233. if (static::checkExistByMobile($data['mobile'])) {
  234. throwError('很抱歉,该手机号已绑定其他账户');
  235. }
  236. }
  237. /**
  238. * @param array $data
  239. * @return string
  240. * @throws BaseException
  241. */
  242. public function saveInfo(array $data): string
  243. {
  244. // 修改手机号需要验证验证码
  245. $userInfo = UserService::getCurrentLoginUser(true);
  246. // 验证信息
  247. $this->checkInfo($data, $userInfo);
  248. $info = UserInfo::detail($userInfo['user_id']);
  249. if (!is_null($info) && $info['school_id'] && $info['school_id'] != $data['school_id']) {
  250. throwError('已认证注册,无法修改学校,请联系客服');
  251. }
  252. if ((!is_null($info) && $info['school_id']) && $userInfo['user_type'] && $data['user_type'] != $userInfo['user_type']) {
  253. throwError('账号类型不可修改');
  254. }
  255. $userInfo->transaction(function () use ($data, $userInfo, $info) {
  256. try {
  257. $userData = [
  258. 'user_id' => $userInfo['user_id'],
  259. 'real_name' => $data['real_name'],
  260. 'gender' => (int)$data['gender'],
  261. 'age' => isset($data['age']) ? intval($data['age']) : 0,
  262. 'student_no' => isset($data['student_no']) ? $data['student_no'] : '',
  263. 'user_login' => isset($data['user_login']) ? $data['user_login'] : '',
  264. 'mobile' => $data['mobile'],
  265. ];
  266. if ($userInfo['user_type'] <= 0 || (is_null($info) || $info['school_id'] <= 0)) {
  267. $userData['user_type'] = (int)$data['user_type'];
  268. }
  269. $userInfo->save($userData);
  270. $infoData = [
  271. 'user_id' => $userInfo['user_id'],
  272. 'school_id' => (int)$data['school_id'],
  273. 'position' => isset($data['position']) ? intval($data['position']) : 0,
  274. 'speciality' => isset($data['speciality']) ? intval($data['speciality']) : 0,
  275. 'qq' => isset($data['qq']) ? $data['qq'] : '',
  276. 'idcard' => isset($data['idcard']) ? $data['idcard'] : '',
  277. 'idcard_front_img' => isset($data['idcard_front_img']) ? $data['idcard_front_img'] : '',
  278. 'work_certify' => isset($data['work_certify']) ? $data['work_certify'] : '',
  279. 'education_certify' => isset($data['education_certify']) ? $data['education_certify'] : '',
  280. 'parent_name' => isset($data['parent_name']) ? $data['parent_name'] : '',
  281. 'admission_year' => isset($data['admission_year']) ? $data['admission_year'] : '',
  282. 'status' => $data['user_type'] != 3 ? 1 : (isset($info['status']) ? $info['status'] : 2),
  283. ];
  284. // 资料是否被修改过
  285. if ($this->checkModifyInfo($data, $info)) {
  286. $infoData['status'] = 2;
  287. }
  288. if (is_null($info)) {
  289. (new UserInfo)->save($infoData);
  290. } else {
  291. $info->save($infoData);
  292. }
  293. // 更新生源学校生源数量
  294. $model = new SourceShool();
  295. $model->setInc(['source_shools_id' => (int)$data['school_id']], 'students_num', 1);
  296. } catch (\Exception $exception) {
  297. throwError('保存失败');
  298. }
  299. });
  300. return $info || $data['user_type'] != 3 ? '保存成功' : '保存成功,等待审核';
  301. }
  302. /**
  303. * 验证重要资料是否已修改
  304. * @param array $data
  305. * @param $info
  306. * @return bool
  307. */
  308. public function checkModifyInfo(array $data, $info): bool
  309. {
  310. if ($data['user_type'] != 3) {
  311. return false;
  312. }
  313. if (is_null($info)) {
  314. return true;
  315. }
  316. $checkFields = ['idcard', 'mobile', 'real_name', 'user_login', 'student_no'];
  317. foreach ($checkFields as $field) {
  318. if (isset($data[$field]) && $info[$field] != $data[$field]) {
  319. return true;
  320. }
  321. }
  322. return false;
  323. }
  324. /**
  325. * 验证用户信息
  326. * @param array $data
  327. * @param array $userInfo
  328. * @return bool
  329. * @throws BaseException
  330. */
  331. private function checkInfo(array $data, UserModel $userInfo): void
  332. {
  333. $validate = new ValidateInfo;
  334. if (!$validate->check($data)) {
  335. throwError($validate->getError());
  336. }
  337. if ($data['user_type'] == 2 && empty($data['parent_name'])) {
  338. throwError('家长姓名不为空');
  339. }
  340. if (empty($data['school_id'])) {
  341. throwError('学校不为空');
  342. }
  343. if ($data['user_type'] == 1) {
  344. /*if(empty($data['admission_year'])){
  345. throwError('请选择入学年份');
  346. }
  347. if(empty($data['education_certify'])){
  348. throwError('请上传教育证明');
  349. }*/
  350. } else if ($data['user_type'] == 3) {
  351. if (empty($data['position'])) {
  352. throwError('请选择职务');
  353. }
  354. /*if(empty($data['work_certify'])){
  355. throwError('请上传职务证明');
  356. }*/
  357. }
  358. if ($userInfo['mobile'] != $data['mobile']) {
  359. if (empty($data['smsCode'])) {
  360. throwError('短信验证码不为空');
  361. }
  362. // 验证短信验证码是否匹配
  363. if ($data['smsCode'] && ($data['smsCode'] != '123456' && !CaptchaApi::checkSms($data['smsCode'], $data['mobile']))) {
  364. throwError('短信验证码不正确');
  365. }
  366. }
  367. $checkId = UserInfo::checkExistByIdcard($data['idcard']);
  368. if ($data['idcard'] && $checkId && $userInfo['user_id'] != $checkId) {
  369. throwError('身份证号码已被使用');
  370. }
  371. /*if(empty($data['idcard_front_img'])){
  372. throwError('请上传身份证明');
  373. }*/
  374. $chekId = self::checkExistByMobile($data['mobile']);
  375. if ($data['mobile'] && $chekId && $userInfo['user_id'] != $chekId) {
  376. throwError('手机号码已被使用');
  377. }
  378. }
  379. /**
  380. * 获取生源学校下的所有生源用户ID
  381. * @param $sourceSchoolId
  382. * @return mixed
  383. */
  384. public static function getSourceUserIds($sourceSchoolId, $ids = [])
  385. {
  386. return self::alias('u')
  387. ->leftJoin('user_info ui', 'ui.user_id=u.user_id')
  388. ->where(['ui.school_id' => $sourceSchoolId, 'u.user_type' => 1, 'u.is_delete' => 0, 'u.status' => 1, 'ui.status' => 1])
  389. ->whereNotIn('u.user_id', $ids)
  390. ->column('u.user_id');
  391. }
  392. }