User.php 48KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Description: 用户
  4. // +----------------------------------------------------------------------
  5. // | Author: Michael_xu | gengxiaoxu@5kcrm.com
  6. // +----------------------------------------------------------------------
  7. namespace app\admin\model;
  8. use app\admin\controller\ApiCommon;
  9. use think\Db;
  10. use app\admin\model\Common;
  11. use com\verify\HonrayVerify;
  12. use think\Cache;
  13. use think\Request;
  14. class User extends Common
  15. {
  16. /**
  17. * 为了数据库的整洁,同时又不影响Model和Controller的名称
  18. * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
  19. */
  20. protected $name = 'admin_user';
  21. protected $createTime = 'create_time';
  22. protected $updateTime = false;
  23. protected $autoWriteTimestamp = true;
  24. protected $insert = [
  25. 'status' => 2,
  26. ];
  27. protected $statusArr = ['禁用','启用','未激活'];
  28. protected $dateFormat = 'Y-m-d';
  29. protected $type = [
  30. 'create_time' => 'timestamp',
  31. 'update_time' => 'timestamp',
  32. ];
  33. /**
  34. * 导入字段
  35. *
  36. * @var array
  37. * @author Ymob
  38. * @datetime 2019-10-25 15:35:25
  39. */
  40. public static $import_field_list = [
  41. [
  42. 'field' => 'username',
  43. 'name' => '手机号(登录名)',
  44. 'form_type' => 'mobile',
  45. 'is_null' => 1,
  46. // 'is_unique' => 1 //guogaobo 导入此字段会进行验重查询调用修改用户方法
  47. ],
  48. [
  49. 'field' => 'password',
  50. 'name' => '密码',
  51. 'form_type' => 'text',
  52. 'is_null' => 1,
  53. ],
  54. [
  55. 'field' => 'realname',
  56. 'name' => '姓名',
  57. 'form_type' => 'text',
  58. 'is_null' => 1,
  59. ],
  60. [
  61. 'field' => 'sex',
  62. 'name' => '性别',
  63. 'form_type' => 'select',
  64. 'setting' => ['男', '女'],
  65. 'is_null' => 0,
  66. ],
  67. [
  68. 'field' => 'email',
  69. 'name' => '邮箱',
  70. 'form_type' => 'email',
  71. 'is_null' => 0,
  72. ],
  73. [
  74. 'field' => 'post',
  75. 'name' => '岗位',
  76. 'form_type' => 'text',
  77. 'is_null' => 0,
  78. ]
  79. ];
  80. /**
  81. * 获取用户所属所有用户组
  82. * @param array $param [description]
  83. */
  84. public function groups()
  85. {
  86. return $this->belongsToMany('group', 'admin_access', 'group_id', 'user_id');
  87. }
  88. public function structureList($structure_id,$str)
  89. {
  90. $str_ids = structureList($structure_id,$str);
  91. return $str_ids;
  92. }
  93. /**
  94. * [getDataList 列表]
  95. * @AuthorHTL
  96. * @param [string] $map [查询条件]
  97. * @param [number] $page [当前页数]
  98. * @param [number] $limit [每页数量]
  99. * @return [description]
  100. */
  101. public function getDataList($request)
  102. {
  103. $structure_status=$request['isNeedChild'];
  104. unset($request['isNeedChild']);
  105. $request = $this->fmtRequest( $request );
  106. $fieldarray = ['search','group_id','structure_id','status','type','page','limit','pageType'];
  107. $map = $request['map'] ? : [];
  108. if (isset($map['search']) && $map['search']) {
  109. $map['user.username|user.realname'] = ['like', '%'.$map['search'].'%'];
  110. }
  111. unset($map['search']);
  112. //角色员工
  113. if ($map['group_id']) {
  114. $group_user_ids = db('admin_access')->where(['group_id' => $map['group_id']])->column('user_id');
  115. if ($map['group_id'] == 1 && !$group_user_ids) {
  116. $group_user_ids = ['1'];
  117. }
  118. $map['user.id'] = array('in',$group_user_ids);
  119. }
  120. $exp = new \think\db\Expression('field(user.status,1,2,0)');
  121. // 默认除去超级管理员
  122. // $map['user.id'] = array('neq', 1);
  123. if($map['structure_id']){
  124. //获取部门下员工列表
  125. if($structure_status==1){
  126. $str_ids = structureList($map['structure_id'],'');
  127. $new_str_ids = rtrim($str_ids,',');
  128. $map['user.structure_id'] = ['in',$new_str_ids]; //$map['structure_id'];
  129. }else{
  130. $map['user.structure_id']=['in',$map['structure_id']];
  131. }
  132. }
  133. $structureData=db('admin_structure')->where('id',$map['structure_id'])->value('owner_user_id');
  134. unset($map['structure_id']);
  135. if ($map['status'] || $map['group_id']) {
  136. if ($map['status'] != 3) {
  137. $map['user.status'] = ($map['status'] !== 'all') ? ($map['status'] ? : ['gt',0]) : ['egt',0];
  138. } else {
  139. $map['user.create_time'] = ['gt', time() - 86400 * 7];
  140. }
  141. } else {
  142. $map['user.status'] = 0;
  143. }
  144. unset($map['status']);
  145. $map['user.type'] = 1;
  146. if(isset($map['type'])) $map['user.type'] == ($map['type'] == '0') ? 0 : 1;
  147. //过滤字段
  148. foreach($fieldarray as $value){
  149. unset($map[$value]);
  150. }
  151. //获取列表
  152. $dataCount = db('admin_user')
  153. ->alias('user')
  154. ->join('__ADMIN_STRUCTURE__ structure', 'structure.id = user.structure_id', 'LEFT')
  155. // ->join('HrmUserDet hud','hud.user_id = user.id','LEFT')
  156. ->where($map)
  157. ->count();
  158. $list = db('admin_user')
  159. ->alias('user')
  160. ->join('__ADMIN_STRUCTURE__ structure', 'structure.id = user.structure_id', 'LEFT')
  161. // ->join('HrmUserDet hud','hud.user_id = user.id','LEFT')
  162. ->limit(($request['page']-1)*$request['limit'], $request['limit'])
  163. ->where($map)
  164. ->field('user.id,user.username,user.img,user.thumb_img,user.realname,user.num,user.email,user.mobile,user.sex,user.structure_id,user.post,user.status,user.parent_id,user.type,user.create_time,structure.name as s_name')
  165. ->order($exp)
  166. ->order('user.id asc')
  167. ->select();
  168. foreach ($list as $k=>$v) {
  169. //直属上级
  170. $list[$k]['status_name'] = $v['status']=='1'?'启用':'禁用';
  171. $parentInfo = [];
  172. $parentInfo = $this->getUserById($v['parent_id']);
  173. $list[$k]['parent_name'] = $v['parent_id'] ? $parentInfo['realname'] : '';
  174. $list[$k]['status_name'] = $v['status'] ? $this->statusArr[$v['status']] : '停用';
  175. //角色
  176. $groupsArr = $this->get($v['id'])->groups;
  177. $groups = [];
  178. $groupids = [];
  179. foreach ($groupsArr as $key=>$val) {
  180. $groups[] = $val['title'];
  181. $groupids[] = $val['id'];
  182. }
  183. $list[$k]['groups'] = $groups ? implode(',',$groups) : '';
  184. $list[$k]['groupids'] = $groupids ? implode(',',$groupids) : '';
  185. $list[$k]['img'] = $v['img'] ? getFullPath($v['img']) : '';
  186. $list[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';
  187. $list[$k]['create_time'] = $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '';
  188. $list[$k]['s_name'] = !empty($v['s_name']) ? $v['s_name'] : '';
  189. $list[$k]['structure_id'] = !empty($v['structure_id']) ? $v['structure_id'] : '';
  190. if($v['id']==1){
  191. $list[$k]['userIdentity']=0;
  192. }elseif($v['id']==$structureData){
  193. $list[$k]['userIdentity']=1;
  194. }else{
  195. $list[$k]['userIdentity']=2;
  196. }
  197. }
  198. //二位数组排序
  199. $last_names = array_column($list,'userIdentity');
  200. array_multisort($last_names,SORT_ASC,$list);
  201. $data = [];
  202. $data['list'] = $list;
  203. $data['dataCount'] = $dataCount;
  204. return $data;
  205. }
  206. /*
  207. *根据字符串展示参与人 use by work
  208. */
  209. public function getDataByStr($idstr)
  210. {
  211. $idArr = stringToArray($idstr);
  212. if (!$idArr) {
  213. return [];
  214. }
  215. $list = $this->field('id,username,realname,thumb_img')->where(['id' => ['in',$idArr]])->select();
  216. foreach($list as $key=>$value){
  217. $list[$key]['thumb_img'] = $value['thumb_img']?getFullPath($value['thumb_img']):'';
  218. }
  219. return $list;
  220. }
  221. /**
  222. * [getDataById 根据主键获取详情]
  223. * @param string $id [主键]
  224. * @return
  225. */
  226. public function getDataById($id = '')
  227. {
  228. $data = Db::name('AdminUser')->find($id);
  229. if (!$data) {
  230. $this->error = '暂无此数据';
  231. return false;
  232. }
  233. unset($data['password']);
  234. unset($data['authkey']);
  235. if($data['structure_id']) {
  236. $structureDet = Db::name('AdminStructure')->field('id,name')->where('id = '.$data['structure_id'].'')->find();
  237. $data['structure_name'] = $structureDet['name'];
  238. } else {
  239. $data['structure_name'] = '暂无';
  240. }
  241. if($data['parent_id']) {
  242. $parentDet = Db::name('AdminUser')->field('id,realname')->where('id = '.$data['parent_id'].'')->find();
  243. $data['parent_name'] = $parentDet['realname'];
  244. } else {
  245. $data['parent_name'] = '暂无';
  246. }
  247. $data['thumb_img'] = getFullPath($data['thumb_img']);
  248. $data['img'] = getFullPath($data['img']);
  249. //$data['groups'] = $this->get($id)->groups();
  250. return $data;
  251. }
  252. /**
  253. * 创建用户
  254. * @param array $param [description]
  255. */
  256. public function createData($param)
  257. {
  258. // 非导入数据
  259. if (request()->action() == 'import') {
  260. $temp = [];
  261. foreach (self::$import_field_list as $key => $val) {
  262. $temp[$val['field']] = $param[$val['field']];
  263. }
  264. $param = $temp;
  265. $param['structure_id'] = 0;
  266. if(db('admin_user')->where('username',$param['username'])->find()){
  267. $this->error = '手机号已存在';
  268. return false;
  269. }
  270. if(db('admin_user')->where('realname',$param['realname'])->find()){
  271. $this->error = '姓名已存在';
  272. return false;
  273. }
  274. } else {
  275. if (empty($param['group_id']) || !is_array($param['group_id'])) {
  276. $this->error = '请至少勾选一个用户组';
  277. return false;
  278. }
  279. }
  280. $nameData=db('admin_user')->where('realname','like','%'.$param['realname'].'%')->column('realname');
  281. if(in_array($param['realname'],$nameData)){
  282. for($j=1;$j<100;$j++){
  283. $name=$param['realname'].$j;
  284. if(in_array($name,$nameData)){
  285. }else{
  286. $name= $param['realname'].$j;
  287. break ;
  288. }
  289. }
  290. $param['realname']= $name;
  291. }else{
  292. $param['realname']= $param['realname'];
  293. }
  294. // 验证
  295. $validate = validate($this->name);
  296. if (!$validate->check($param)) {
  297. $this->error = $validate->getError();
  298. return false;
  299. }
  300. $syncModel = new \app\admin\model\Sync();
  301. $this->startTrans();
  302. try {
  303. $salt = substr(md5(time()),0,4);
  304. $param['salt'] = $salt;
  305. if (!$param['password']) {
  306. $password = $param['username'];
  307. } else {
  308. $password = $param['password'];
  309. }
  310. $param['password'] = user_md5($password, $salt, $param['username']);
  311. $param['type'] = 1;
  312. $param['mobile'] = $param['username'];
  313. $this->data($param)->allowField(true)->isUpdate(false)->save();
  314. $user_id = (int) $this->getLastInsId();
  315. //员工档案
  316. $data['user_id'] = $param['user_id'];
  317. unset($param['user_id']);
  318. $data['user_id'] = $user_id;
  319. $data['mobile'] = $param['username'];
  320. $data['email'] = $param['email'] ? : '';
  321. $data['sex'] = $param['sex'] ? : '';
  322. $data['create_time'] = time();
  323. Db::name('HrmUserDet')->insert($data);
  324. $userGroups = [];
  325. foreach ($param['group_id'] as $k => $v) {
  326. $userGroup['user_id'] = $user_id;
  327. $userGroup['group_id'] = $v;
  328. $userGroups[] = $userGroup;
  329. }
  330. if ($userGroups) {
  331. Db::name('admin_access')->insertAll($userGroups);
  332. }
  333. $this->commit();
  334. $param['user_id'] = $data['user_id'];
  335. $resSync = $syncModel->syncData($param);
  336. # 添加记录
  337. $user=new ApiCommon();
  338. $userInfo=$user->userInfo;
  339. SystemActionLog($userInfo['id'], 'admin_user','employee', $user_id, 'save', $param['realname'], '', '','新增用户:'.$param['realname']);
  340. return true;
  341. } catch(\Exception $e) {
  342. $this->rollback();
  343. $this->error = '添加失败';
  344. return false;
  345. }
  346. }
  347. //导入成为正式用户
  348. public function beusers($request)
  349. {
  350. if ($request['userlist']&&is_array($request['userlist'])) {
  351. $flag = true;
  352. foreach ($request['userlist'] as $value) {
  353. $userInfo = Db::name('AdminUser')->where('id = '.$value.'')->find();
  354. $userDet = Db::name('HrmUserDet')->where('user_id = '.$value.'')->find();
  355. $temp['status'] = 1;
  356. $temp['type'] = 1;
  357. $temp['username'] = $userDet['mobile'];
  358. $salt = substr(md5(time()),0,4);
  359. $temp['salt'] = $salt;
  360. $password = $userDet['mobile'];
  361. $temp['password'] = user_md5($password, $salt, $temp['username']);
  362. $flag = $flag && Db::name('AdminUser')->where('id ='.$value)->update($temp);
  363. }
  364. if ($flag) {
  365. return true;
  366. } else {
  367. $this->error = '操作失败';
  368. return false;
  369. }
  370. } else {
  371. $this->error = '参数错误';
  372. return false;
  373. }
  374. }
  375. /**
  376. * 通过id修改用户
  377. * @param array
  378. */
  379. public function updateDataById($param, $id)
  380. {
  381. $user=new ApiCommon();
  382. $user_id=$user->userInfo;
  383. if ($param['user_id']) {
  384. //修改个人信息
  385. $data['email'] = $param['email'];
  386. $data['sex'] = $param['sex'];
  387. // $data['mobile'] = $param['username'];
  388. $userInfo=db('admin_user')->where(['username' => $param['username'],'id' => ['neq',$param['user_id']]])->find();
  389. if ($userInfo) {
  390. $this->error = '手机号已存在';
  391. return false;
  392. }
  393. Db::name('HrmUserDet')->where(['user_id' => $param['user_id']])->update($data);
  394. $data['realname'] = $param['realname'];
  395. $data['post'] = $param['post'];
  396. $flag = $this->where(['id' => $param['user_id']])->update($data);
  397. if ($flag==0 || $flag==1) {
  398. SystemActionLog($user_id['id'],'admin_user', 'employee', $param['user_id'], 'update', $param['realname'], '', '','编辑了:'.$param['realname']);
  399. return true;
  400. } else {
  401. $this->error = '保存失败';
  402. return false;
  403. }
  404. } else {
  405. // 不能操作超级管理员
  406. // if ($id == 1) {
  407. // $this->error = '非法操作';
  408. // return false;
  409. // }
  410. $checkData = $this->get($id);
  411. $userInfo = $checkData->data;
  412. if (!$checkData) {
  413. $this->error = '暂无此数据';
  414. return false;
  415. }
  416. if (request()->action() != 'import') {
  417. if (empty($param['group_id'])) {
  418. $this->error = '请至少勾选一个用户组';
  419. return false;
  420. }
  421. }
  422. $subUserId = getSubUserId(true, 0, $id);
  423. if ((int)$param['parent_id'] == (int)$id) {
  424. $this->error = '直属上级不能是自己';
  425. return false;
  426. }
  427. if ((int)$param['parent_id'] !== 1 && in_array($param['parent_id'],$subUserId)) {
  428. $this->error = '直属上级不能是自己或下属';
  429. return false;
  430. }
  431. if (db('admin_user')->where(['id' => ['neq',$id],'username' => $param['username']])->find()) {
  432. $this->error = '手机号已存在';
  433. return false;
  434. }
  435. $this->startTrans();
  436. try {
  437. $accessModel = model('Access');
  438. if ($param['group_id']) {
  439. //角色员工关系处理
  440. $accessModel->userGroup($id, $param['group_id'], 'update');
  441. }
  442. if (!empty($param['password'])) {
  443. $salt = $userInfo['salt'];
  444. $param['password'] = user_md5($param['password'], $salt, $param['username']);
  445. }
  446. $this->allowField(true)->save($param, ['id' => $id]);
  447. $this->commit();
  448. Cache::rm('user_info' . $id);
  449. SystemActionLog($user_id['id'], 'admin_user','employee', $id, 'update', $userInfo['realname'], '', '','编辑了:'.$userInfo['realname']);
  450. // $data['mobile'] = $param['username'];
  451. $data['email'] = $param['email'];
  452. $data['sex'] = $param['sex'];
  453. $data['update_time'] = time();
  454. $flagg = Db::name('HrmUserDet')->where('user_id = '.$id)->update($data);
  455. return true;
  456. } catch(\Exception $e) {
  457. $this->rollback();
  458. $this->error = '编辑失败';
  459. return false;
  460. }
  461. }
  462. }
  463. /**
  464. * [login 登录]
  465. * @AuthorHTL
  466. * @DateTime
  467. * @param [string] $u_username [账号]
  468. * @param [string] $u_pwd [密码]
  469. * @param [string] $verifyCode [验证码]
  470. * @param Boolean $isRemember [是否记住密码]
  471. * @param Boolean $type [是否重复登录]
  472. * @param array $paramArr
  473. * @return [type] [description]
  474. */
  475. public function login($username, $password, $verifyCode = '', $isRemember = false, $type = false, $authKey = '', $paramArr = [])
  476. {
  477. if ($paramArr['dingCode']) {
  478. $dingtalkModel = new \app\admin\model\Dingtalk();
  479. $username = $dingtalkModel->sign($paramArr['dingCode']);
  480. if (!$username) {
  481. $this->error = $dingtalkModel->getError();;
  482. return false;
  483. }
  484. } else {
  485. if (!$password){
  486. $this->error = '密码不能为空';
  487. return false;
  488. }
  489. }
  490. if (config('IDENTIFYING_CODE') && !$type) {
  491. if (!$verifyCode) {
  492. $this->error = '验证码不能为空';
  493. return false;
  494. }
  495. $captcha = new HonrayVerify(config('captcha'));
  496. if (!$captcha->check($verifyCode)) {
  497. $this->error = '验证码错误';
  498. return false;
  499. }
  500. }
  501. $map['username'] = $username;
  502. $map['type'] = 1;
  503. $userInfo = $this->where($map)->find();
  504. if (!$userInfo) {
  505. $this->error = '帐号不存在';
  506. return false;
  507. }
  508. // 登录记录
  509. $login_record = new LoginRecord();
  510. $login_record->user_id = $userInfo['id'];
  511. // 三次出错,十五分钟禁止登录
  512. if (!$login_record->verify()) {
  513. $this->error = $login_record->error;
  514. return false;
  515. }
  516. $userInfo['thumb_img'] = $userInfo['thumb_img'] ? getFullPath($userInfo['thumb_img']) : '';
  517. if (user_md5($password, $userInfo['salt'], $userInfo['username']) !== $userInfo['password'] && !$paramArr['dingCode']) {
  518. $this->error = '账号或密码错误!';
  519. $login_record->createRecord(LoginRecord::TYPE_PWD_ERROR);
  520. return false;
  521. }
  522. if ($userInfo['status'] === 0) {
  523. $this->error = '帐号已被禁用';
  524. $login_record->createRecord(LoginRecord::TYPE_USER_BANNED);
  525. return false;
  526. }
  527. $platform = $paramArr['platform'] ? '_'.$paramArr['platform'] : ''; //请求平台(mobile,ding)
  528. $login_record->createRecord($platform,LoginRecord::TYPE_SUCCESS);
  529. // 获取菜单和权限
  530. $dataList = $this->getMenuAndRule($userInfo['id']);
  531. if ($isRemember || $type) {
  532. $secret['username'] = $username;
  533. $secret['password'] = $password;
  534. $data['rememberKey'] = encrypt($secret);
  535. }
  536. //登录有效时间
  537. $cacheConfig = config('cache');
  538. $loginExpire = !empty($cacheConfig['expire']) ? $cacheConfig['expire'] : 86400 * 30;
  539. // 保存缓存
  540. session_start();
  541. $info['userInfo'] = $userInfo;
  542. $info['sessionId'] = session_id();
  543. $authKey = user_md5($userInfo['username'].$userInfo['password'].$info['sessionId'], $userInfo['salt']);
  544. // $info['_AUTH_LIST_'] = $dataList['rulesList'];
  545. $info['authKey'] = $authKey;
  546. //删除旧缓存
  547. if (Cache::get('Auth_'.$userInfo['authkey'].$platform)) {
  548. Cache::rm('Auth_'.$userInfo['authkey'].$platform);
  549. }
  550. Cache::set('Auth_'.$authKey.$platform, $info, $loginExpire);
  551. unset($userInfo['authkey']);
  552. // 返回信息
  553. $data['authKey'] = $authKey;
  554. $data['sessionId'] = $info['sessionId'];
  555. $data['userInfo'] = $userInfo;
  556. $data['authList'] = $dataList['authList'];
  557. $data['menusList'] = $dataList['menusList'];
  558. $data['loginExpire'] = $loginExpire;
  559. //保存authKey信息
  560. $userData = [];
  561. $userData['authkey'] = $authKey;
  562. $userData['authkey_time'] = time()+$loginExpire;
  563. //把状态未激活至为启用
  564. if ($userInfo['status'] == 2) {
  565. $userData['status'] = 1;
  566. }
  567. $this->where(['id' => $userInfo['id']])->update($userData);
  568. return $data;
  569. }
  570. /**
  571. * 修改密码
  572. * @param array $param [description]
  573. */
  574. public function updatePaw($userInfo, $old_pwd, $new_pwd)
  575. {
  576. if (!$old_pwd) {
  577. $this->error = '请输入旧密码';
  578. return false;
  579. }
  580. if (!$new_pwd) {
  581. $this->error = '请输入新密码';
  582. return false;
  583. }
  584. if ($new_pwd == $old_pwd) {
  585. $this->error = '新旧密码不能一致';
  586. return false;
  587. }
  588. //登录有效时间
  589. $cacheConfig = config('cache');
  590. $loginExpire = $cacheConfig['expire'] ? : 86400 * 3;
  591. $password = $this->where('id', $userInfo['id'])->value('password');
  592. if (user_md5($old_pwd, $userInfo['salt'], $userInfo['username']) != $password) {
  593. $this->error = '原密码错误';
  594. return false;
  595. }
  596. if (user_md5($new_pwd, $userInfo['salt'], $userInfo['username']) == $password) {
  597. $this->error = '密码没改变';
  598. return false;
  599. }
  600. if ($this->where('id', $userInfo['id'])->setField('password', user_md5($new_pwd, $userInfo['salt'], $userInfo['username']))) {
  601. $syncData = [];
  602. $syncModel = new \app\admin\model\Sync();
  603. $syncData['user_id'] = $userInfo['id'];
  604. $syncData['salt'] = $userInfo['salt'];
  605. $syncData['password'] = user_md5($new_pwd, $userInfo['salt'], $userInfo['username']);
  606. $resSync = $syncModel->syncData($syncData);
  607. $userInfo = $this->where('id', $userInfo['id'])->find();
  608. # 添加记录
  609. $user=new ApiCommon();
  610. $user_id=$user->userInfo;
  611. SystemActionLog($user_id['id'], 'admin_user','employee', $userInfo['id'], 'update', $userInfo['realname'], '', '','重置了密码:'.$userInfo['realname']);
  612. // 重新设置缓存
  613. session_start();
  614. $cache['userInfo'] = $userInfo;
  615. $cache['authKey'] = user_md5($userInfo['username'].$userInfo['password'].session_id(), $userInfo['salt']);
  616. cache('Auth_'.$cache['authKey'], null);
  617. cache('Auth_'.$cache['authKey'], $cache, $loginExpire);
  618. return $cache['authKey'];//把auth_key传回给前端
  619. }
  620. $this->error = '修改失败';
  621. return false;
  622. }
  623. //根据IDs批量设置密码
  624. public function updatePwdById($param)
  625. {
  626. $syncModel = new \app\admin\model\Sync();
  627. $flag = true;
  628. $userInfo = new ApiCommon();
  629. $user_id=$userInfo->userInfo;
  630. foreach ($param['id'] as $value) {
  631. $password = '';
  632. $userInfo = db('admin_user')->where(['id' => $value])->find();
  633. $salt = substr(md5(time()),0,4);
  634. $temp['salt'] = $salt;
  635. $temp['password']= $password = user_md5($param['password'], $salt, $userInfo['username']);
  636. $flag = $flag && Db::name('AdminUser')->where('id ='.$value)->update($temp);
  637. $syncData = [];
  638. $syncData['user_id'] = $value;
  639. $syncData['salt'] = $salt;
  640. $syncData['password'] = $password;
  641. $resSync = $syncModel->syncData($syncData);
  642. }
  643. if ($flag) {
  644. foreach ($param['id'] as $v){
  645. $userInfo = db('admin_user')->where(['id' => $v])->find();
  646. # 添加记录
  647. $user=new ApiCommon();
  648. $user_id=$user->userInfo;
  649. SystemActionLog($user_id['id'], 'admin_user','employee', $v, 'update',$userInfo['realname'],'', '', '重置了密码:'.$userInfo['realname']);
  650. }
  651. return $flag;
  652. } else {
  653. $this->error ='修改失败,请稍后重试';
  654. return false;
  655. }
  656. }
  657. /**
  658. * 获取菜单和权限 protected
  659. *
  660. * @param $u_id
  661. * @return array
  662. * @throws \think\db\exception\DataNotFoundException
  663. * @throws \think\db\exception\ModelNotFoundException
  664. * @throws \think\exception\DbException
  665. */
  666. public function getMenuAndRule($u_id)
  667. {
  668. $menusList = [];
  669. $ruleMap = [];
  670. $adminTypes = adminGroupTypes($u_id);
  671. if (in_array(1,$adminTypes)) {
  672. $map['status'] = 1;
  673. $menusList = Db::name('admin_menu')->where($map)->order('sort asc')->select();
  674. } else {
  675. $groups = $this->get($u_id)->groups;
  676. $ruleIds = [];
  677. foreach ($groups as $k => $v) {
  678. if (stringToArray($v['rules'])) {
  679. $ruleIds = array_merge($ruleIds, stringToArray($v['rules']));
  680. }
  681. }
  682. $ruleIds = array_unique($ruleIds);
  683. $ruleMap['id'] = array('in', $ruleIds);
  684. $ruleMap['status'] = 1;
  685. }
  686. $newRuleIds = [];
  687. // 重新设置ruleIds,除去部分已删除或禁用的权限。
  688. $rules = Db::name('admin_rule')->where($ruleMap)->select();
  689. // $ruless = Db::name('admin_rule')->where($ruleMap)->where(['level'=>2,'pid'=>0])->column('name');
  690. foreach ($rules as $k => $v) {
  691. $newRuleIds[] = $v['id'];
  692. $rules[$k]['name'] = strtolower($v['name']);
  693. }
  694. //菜单管理(弃用)
  695. // $menuMap['status'] = 1;
  696. // $menuMap['rule_id'] = array('in',$newRuleIds);
  697. // $menusList = Db::name('admin_menu')->where($menuMap)->order('sort asc')->select();
  698. $ret = [];
  699. //处理菜单成树状
  700. $tree = new \com\Tree();
  701. //处理规则成树状
  702. $rulesList = $tree->list_to_tree($rules, 'id', 'pid', 'child', 0, true, array('pid'));
  703. //权限数组
  704. $authList = rulesListToArray($rulesList, $newRuleIds);
  705. //应用控制
  706. $adminConfig = db('admin_config')->where(['pid' => 0,'status' => 1])->column('module');
  707. $adminConfig = $adminConfig ? array_merge($adminConfig,['bi','admin']) : ['bi','admin'];
  708. # 通讯录
  709. if (in_array('book', $adminConfig) && !empty($authList['oa']['addresslist']['index'])) {
  710. $authList['oa']['book']['index'] = true;
  711. }
  712. # 商业智能权限细化
  713. if ($authList['bi']) {
  714. if (!in_array('taskExamine',$adminConfig) && !in_array('crm',$adminConfig)) {
  715. unset($authList['bi']);
  716. } else {
  717. foreach ($authList['bi'] as $key=>$val) {
  718. if (!in_array('taskExamine',$adminConfig)) {
  719. unset($authList['bi']['oa']);
  720. }
  721. if (!in_array('crm',$adminConfig)) {
  722. unset($authList['bi']['customer']);
  723. unset($authList['bi']['business']);
  724. unset($authList['bi']['product']);
  725. unset($authList['bi']['achievement']);
  726. unset($authList['bi']['contract']);
  727. unset($authList['bi']['portrait']);
  728. unset($authList['bi']['ranking']);
  729. }
  730. }
  731. }
  732. } else {
  733. unset($authList['bi']);
  734. }
  735. # 任务审批
  736. if (in_array('taskExamine', $adminConfig) ) {
  737. $authList['oa']['taskExamine'] = (Object)[];
  738. }
  739. # 项目
  740. if (in_array('work', $adminConfig)) {
  741. $authList['project']['projectLabelManage']['projectLabelAdd'] = !empty($authList['work']['work']['save']);
  742. $authList['project']['projectLabelManage']['projectLabelDelete'] = !empty($authList['work']['work']['save']);
  743. $authList['project']['projectLabelManage']['projectLabelUpdate'] = !empty($authList['work']['work']['save']);
  744. $authList['project']['projectManage']['save'] = !empty($authList['work']['work']['save']);
  745. }
  746. # 日志
  747. if (in_array('log', $adminConfig)) {
  748. $authList['oa']['log'] = (Object)[];
  749. }
  750. # 日历
  751. if (in_array('calendar', $adminConfig)) {
  752. $authList['oa']['calendar'] = (Object)[];
  753. }
  754. # 公海权限
  755. $structureId = db('admin_user')->where('id', $u_id)->value('structure_id');
  756. $poolStatus = db('crm_customer_pool')->whereLike('admin_user_ids', '%,' . $u_id . ',%')
  757. ->whereOr('user_ids', 'like', '%,' . $u_id . ',%')
  758. ->whereOr('department_ids', 'like', '%,' . $structureId . ',%')
  759. ->value('pool_id');
  760. if (!empty($poolStatus)) $authList['crm']['pool'] = ['index' => true];
  761. $ret['authList'] = $this->resetAuthorityFiled($authList);
  762. $res['manage'] = $rules;
  763. return $ret;
  764. }
  765. /**
  766. * todo 应前端要求修改部分权限字段,与java的权限字段保持一致。
  767. *
  768. * @param $authList
  769. * @return mixed
  770. */
  771. private function resetAuthorityFiled($authList)
  772. {
  773. # 客户
  774. if (isset($authList['crm']['customer']['deal_status'])) {
  775. $authList['crm']['customer']['dealStatus'] = $authList['crm']['customer']['deal_status'];
  776. unset($authList['crm']['customer']['deal_status']);
  777. }
  778. if (isset($authList['crm']['customer']['nearby'])) {
  779. $authList['crm']['customer']['nearbyCustomer'] = $authList['crm']['customer']['nearby'];
  780. unset($authList['crm']['customer']['nearby']);
  781. }
  782. # 公海权限
  783. $authList['crm']['customer']['pool'] = !empty($authList['crm']['pool']['index']);;
  784. # 跟进记录
  785. $authList['crm']['followRecord'] = $authList['crm']['activity'];
  786. # 合同
  787. if (isset($authList['crm']['contract']['discard'])) {
  788. $authList['crm']['contract']['discard'] = false;
  789. }
  790. # 发票
  791. if (isset($authList['crm']['invoice']['setinvoice'])) {
  792. $authList['crm']['invoice']['updateInvoiceStatus'] = $authList['crm']['invoice']['setinvoice'];
  793. }
  794. # 发票抬头权限
  795. if (!empty($authList['crm']['invoice']['index'])) {
  796. $authList['crm']['invoiceTitle']['index'] = true;
  797. }
  798. unset($authList['work']['work']);
  799. unset($authList['work']['task']);
  800. unset($authList['work']['taskclass']);
  801. # admin:system
  802. if (!empty($authList['admin']['system']['index'])) {
  803. $authList['admin']['system']['read'] = $authList['admin']['system']['index'];
  804. unset($authList['admin']['system']['index']);
  805. }
  806. if (!empty($authList['admin']['system']['save'])) {
  807. $authList['admin']['system']['update'] = $authList['admin']['system']['save'];
  808. }
  809. # admin:configSet
  810. if (!empty($authList['admin']['configset']['index'])) {
  811. $authList['admin']['configSet']['read'] = $authList['admin']['configset']['index'];
  812. }
  813. if (!empty($authList['admin']['configset']['update'])) {
  814. $authList['admin']['configSet']['update'] = $authList['admin']['configset']['update'];
  815. }
  816. unset($authList['admin']['configset']);
  817. # admin:users
  818. if (!empty($authList['admin']['users']['index'])) {
  819. $authList['admin']['users']['read'] = $authList['admin']['users']['index'];
  820. unset($authList['admin']['users']['index']);
  821. }
  822. if (!empty($authList['admin']['users']['enables'])) {
  823. $authList['admin']['users']['userEnables'] = $authList['admin']['users']['enables'];
  824. unset($authList['admin']['users']['enables']);
  825. }
  826. if (!empty($authList['admin']['users']['save'])) {
  827. $authList['admin']['users']['userSave'] = $authList['admin']['users']['save'];
  828. unset($authList['admin']['users']['save']);
  829. }
  830. if (!empty($authList['admin']['users']['update'])) {
  831. $authList['admin']['users']['userUpdate'] = $authList['admin']['users']['update'];
  832. unset($authList['admin']['users']['update']);
  833. }
  834. if (!empty($authList['admin']['users']['structures_save'])) {
  835. $authList['admin']['users']['deptSave'] = $authList['admin']['users']['structures_save'];
  836. unset($authList['admin']['users']['structures_save']);
  837. }
  838. if (!empty($authList['admin']['users']['structures_update'])) {
  839. $authList['admin']['users']['deptUpdate'] = $authList['admin']['users']['structures_update'];
  840. unset($authList['admin']['users']['structures_update']);
  841. }
  842. if (!empty($authList['admin']['users']['structures_delete'])) {
  843. $authList['admin']['users']['deptDelete'] = $authList['admin']['users']['structures_delete'];
  844. unset($authList['admin']['users']['structures_delete']);
  845. }
  846. # admin:group 角色权限管理
  847. if (!empty($authList['admin']['groups'])) {
  848. $authList['admin']['permission'] = $authList['admin']['groups'];
  849. unset($authList['admin']['groups']);
  850. }
  851. # admin:examine_flow
  852. if (!empty($authList['admin']['examine_flow'])) {
  853. $authList['admin']['examineFlow'] = $authList['admin']['examine_flow'];
  854. unset($authList['admin']['examine_flow']);
  855. }
  856. # admin:printing
  857. if (!empty($authList['admin']['crm']['printing'])) {
  858. $authList['admin']['crm']['print'] = $authList['admin']['crm']['printing'];
  859. unset($authList['admin']['crm']['printing']);
  860. }
  861. # admin:work
  862. if (!empty($authList['admin']['work']['work'])) {
  863. $authList['admin']['work']['update'] = $authList['admin']['work']['work'];
  864. unset($authList['admin']['work']['work']);
  865. }
  866. # admin:log
  867. if (isset($authList['admin']['adminlog']['loginlog'])) {
  868. $authList['admin']['adminLog']['loginLog'] = $authList['admin']['adminlog']['loginlog'];
  869. unset($authList['admin']['adminlog']['loginlog']);
  870. }
  871. if (isset($authList['admin']['adminlog']['actionrecord'])) {
  872. $authList['admin']['adminLog']['actionRecord'] = $authList['admin']['adminlog']['actionrecord'];
  873. unset($authList['admin']['adminlog']['actionrecord']);
  874. }
  875. if (isset($authList['admin']['adminlog']['systemlog'])) {
  876. $authList['admin']['adminLog']['systemLog'] = $authList['admin']['adminlog']['systemlog'];
  877. unset($authList['admin']['adminlog']['systemlog']);
  878. }
  879. unset($authList['admin']['adminlog']);
  880. # admin:initialize
  881. if (!empty($authList['admin']['initialize'])) {
  882. $authList['admin']['init']['initData'] = $authList['admin']['initialize']['update'];
  883. $authList['admin']['init']['index'] = $authList['admin']['initialize']['index'];
  884. unset($authList['admin']['initialize']);
  885. }
  886. # admin
  887. if (!empty($authList['admin'])) {
  888. $authList['manage'] = $authList['admin'];
  889. $adminAuth = [
  890. 'configSet.read', 'crm.achievement', 'crm.field', 'crm.pool', 'crm.setting',
  891. 'examineFlow.index', 'init.initData', 'oa.examine', 'system.read', 'users.read',
  892. 'work.update','permission.update'
  893. ];
  894. foreach ($authList['manage'] AS $key1 => $value1) {
  895. foreach ($value1 AS $key2 => $value2) {
  896. if (in_array($key1.'.'.$key2, $adminAuth)) {
  897. $authList['manage']['other_rule'] = [
  898. 'setwelcome' => true,
  899. 'setworklogrule' => true,
  900. 'welcome' => true,
  901. 'worklogrule' => true
  902. ];
  903. }
  904. }
  905. }
  906. }
  907. if (empty($authList['manage']['other_rule'])) unset($authList['manage']);
  908. unset($authList['admin']);
  909. # 通讯录
  910. $authList['email'] = (Object)[];
  911. $authList['hrm'] = (Object)[];
  912. $authList['jxc'] = (Object)[];
  913. $authList['knowledge'] = (Object)[];
  914. return $authList;
  915. }
  916. /**
  917. * 获取权限结构数组
  918. * @param
  919. */
  920. public function getRulesList($uid)
  921. {
  922. $ruleMap = [];
  923. $adminTypes = adminGroupTypes($uid);
  924. if (in_array(1,$adminTypes)) {
  925. $map['status'] = 1;
  926. } else {
  927. $groups = $this->get($uid)->groups;
  928. $ruleIds = [];
  929. foreach($groups as $k => $v) {
  930. if (stringToArray($v['rules'])) {
  931. $ruleIds = array_merge($ruleIds, stringToArray($v['rules']));
  932. }
  933. }
  934. $ruleIds = array_unique($ruleIds);
  935. $ruleMap['id'] = array('in', $ruleIds);
  936. $ruleMap['status'] = 1;
  937. }
  938. $newRuleIds = [];
  939. // 重新设置ruleIds,除去部分已删除或禁用的权限。
  940. $rules = Db::name('admin_rule')->where($ruleMap)->select();
  941. foreach ($rules as $k => $v) {
  942. $newRuleIds[] = $v['id'];
  943. $rules[$k]['name'] = strtolower($v['name']);
  944. }
  945. //处理规则成树状
  946. $tree = new \com\Tree();
  947. $rulesList = $tree->list_to_tree($rules, 'id', 'pid', 'child', 0, true, array('pid'));
  948. $rulesList = rulesDeal($rulesList);
  949. return $rulesList ? : [];
  950. }
  951. /**
  952. * 获取用户所属角色(用户组)
  953. * @param
  954. */
  955. public function getGroupTypeByAction($uid, $m, $c, $a)
  956. {
  957. //根据$m,$c,$a 获取对应的$a 的rule_id
  958. $rulesList = $this->getRulesList($uid);
  959. if (!in_array($m.'-'.$c.'-'.$a, $rulesList)) {
  960. return false;
  961. }
  962. $mRuleId = db('admin_rule')->where(['name'=>$m,'level'=>1])->value('id');
  963. $cRuleId = db('admin_rule')->where(['name'=>$c,'level'=>2,'pid'=>$mRuleId])->value('id');
  964. $aRuleId = db('admin_rule')->where(['name'=>$a,'level'=>3,'pid'=>$cRuleId])->value('id');
  965. //获取用户组
  966. $groups = $this->get($uid)->groups;
  967. if (!$groups) {
  968. return false;
  969. }
  970. $groupTypes = [];
  971. foreach ($groups as $g) {
  972. if (in_array($aRuleId, explode(',', trim($g['rules'], ',')))) {
  973. $groupTypes[] = $g['type'];
  974. }
  975. }
  976. return $groupTypes ? : [];
  977. }
  978. /**
  979. * 获取有此权限的角色
  980. * @param
  981. */
  982. public function getAllUserByAction($m, $c, $a)
  983. {
  984. $mRuleId = db('admin_rule')->where(['name'=>$m,'level'=>1])->value('id');
  985. $cRuleId = db('admin_rule')->where(['name'=>$c,'level'=>2,'pid'=>$mRuleId])->value('id');
  986. $aRuleId = db('admin_rule')->where(['name'=>$a,'level'=>3,'pid'=>$cRuleId])->value('id');
  987. $groups = db('admin_group')->where(['rules' => ['in',$aRuleId]])->column('id');
  988. $userIds = db('admin_access')->where(['group_id' => ['in',$groups]])->column('user_id');
  989. if (!$userIds) {
  990. //查询管理员
  991. $userIds = db('admin_user')->where(['id' => 1])->column('id');
  992. }
  993. return $userIds;
  994. }
  995. /**
  996. * 根据部门获取部门的userId
  997. * @param $strId 部门ID
  998. * @param $type 2时包含所有下属部门
  999. */
  1000. public function getSubUserByStr($structure_id, $type = 1)
  1001. {
  1002. $allStrIds = (array) $structure_id;
  1003. if ($type == 2) {
  1004. $structureModel = new \app\admin\model\Structure();
  1005. foreach ($allStrIds as $v) {
  1006. $allSubStrIds = [];
  1007. $allSubStrIds = $structureModel->getAllChild($v);
  1008. if ($allSubStrIds) {
  1009. $allStrIds = array_merge($allStrIds, $allSubStrIds); //全部关联部门(包含下属部门)
  1010. }
  1011. }
  1012. }
  1013. $userIds = db('admin_user')->where(['structure_id' => ['in',$allStrIds]])->column('id');
  1014. return $userIds ? : [];
  1015. }
  1016. /**
  1017. * [getUserById 根据主键获取详情]
  1018. * @param
  1019. * @return
  1020. */
  1021. public function getUserById($id = '')
  1022. {
  1023. $data = Db::name('AdminUser')
  1024. ->alias('user')
  1025. ->join('__ADMIN_STRUCTURE__ structure', 'structure.id = user.structure_id', 'LEFT')
  1026. ->where(['user.id' => $id])
  1027. ->field([
  1028. 'user.id',
  1029. 'username',
  1030. 'img',
  1031. 'thumb_img',
  1032. 'realname',
  1033. 'parent_id',
  1034. 'structure.name' => 'structure_name',
  1035. 'structure.id' => 'structure_id'
  1036. ])
  1037. // ->cache('user_info' . $id, null, 'user_info')
  1038. ->find();
  1039. $data['img'] = $data['img'] ? getFullPath($data['img']) : '';
  1040. $data['thumb_img'] = $data['thumb_img'] ? getFullPath($data['thumb_img']) : '';
  1041. return $data ? : [];
  1042. }
  1043. /**
  1044. * [getUserNameById 根据主键获取详情]
  1045. * @param
  1046. * @return
  1047. */
  1048. public function getUserNameById($id = '')
  1049. {
  1050. $data = $this->where(['id' => $id])->value('realname');
  1051. return $data ? : '查看详情';
  1052. }
  1053. /**
  1054. * [getUserNameByArr 根据主键获取详情]
  1055. * @param
  1056. * @return
  1057. */
  1058. public function getUserNameByArr($ids = [])
  1059. {
  1060. if (!is_array($ids)) {
  1061. $idArr[] = $ids;
  1062. } else {
  1063. $idArr = $ids;
  1064. }
  1065. $data = $this->where(['id' => array('in', $idArr)])->column('realname');
  1066. return $data ? : [];
  1067. }
  1068. /**
  1069. * [getAdminId 获取管理员ID]
  1070. * @param
  1071. * @return
  1072. */
  1073. public function getAdminId()
  1074. {
  1075. $adminGroupUser = db('admin_access')->where(['group_id' => 1])->column('user_id');
  1076. $userIDs = $adminGroupUser ? array_merge($adminGroupUser, [1]) : [1];
  1077. return $userIDs ? : [1];
  1078. }
  1079. /**
  1080. * [getUserByIdArr 根据ID数组获取列表]
  1081. * @param
  1082. * @return
  1083. */
  1084. public function getUserByIdArr($ids = [])
  1085. {
  1086. $list = $this
  1087. ->alias('user')
  1088. ->join('__ADMIN_STRUCTURE__ structure', 'structure.id = user.structure_id', 'LEFT')
  1089. ->where(['user.id' => ['in', $ids]])->field('user.id,username,img,thumb_img,realname,parent_id,structure.name as structure_name,structure.id as structure_id')->select();
  1090. return $list ? : [];
  1091. }
  1092. /**
  1093. * [getUserByPer 获取权限范围的user_id]
  1094. * @param
  1095. * @return
  1096. */
  1097. public function getUserByPer($m = '', $c = '', $a = ''){
  1098. $request = Request::instance();
  1099. $header = $request->header();
  1100. $authKey = $header['authkey'];
  1101. $m = $m ? strtolower($m) : strtolower($request->module());
  1102. $c = $c ? strtolower($c) : strtolower($request->controller());
  1103. $a = $a ? strtolower($a) : strtolower($request->action());
  1104. $cache = cache('Auth_'.$authKey);
  1105. if (!$cache) {
  1106. return false;
  1107. }
  1108. $userInfo = $cache['userInfo'];
  1109. //用户所属用户组类别(数组)
  1110. $groupTypes = $this->getGroupTypeByAction($userInfo['id'], $m, $c, $a);
  1111. //数组去重
  1112. $groupTypes = $groupTypes ? array_unique($groupTypes) : [];
  1113. //用户组类别(1本人,2本人及下属,3本部门,4本部门及下属部门,5全部)
  1114. $adminIds = $this->getAdminId();
  1115. $userIds = [];
  1116. if (in_array($userInfo['id'],$adminIds)) {
  1117. $userIds = getSubUserId(true, 1);
  1118. } else {
  1119. if (!$groupTypes) {
  1120. return [];
  1121. }
  1122. if (in_array(5, $groupTypes)) {
  1123. $userIds = getSubUserId(true, 1);
  1124. } else {
  1125. foreach ($groupTypes as $v) {
  1126. if ($v == 1) {
  1127. $userIds = [$userInfo['id']];
  1128. } elseif ($v == 2) {
  1129. $userIds = getSubUserId();
  1130. } elseif ($v == 3) {
  1131. $userIds = $this->getSubUserByStr($userInfo['structure_id']);
  1132. } elseif ($v == 4) {
  1133. $userIds = $this->getSubUserByStr($userInfo['structure_id'], 2);
  1134. }
  1135. }
  1136. }
  1137. }
  1138. return $userIds ? : [];
  1139. }
  1140. /*
  1141. *根据部门ID获取员工列表
  1142. *
  1143. */
  1144. public function getUserListByStructureId($structure_id='')
  1145. {
  1146. $map =array();
  1147. if($structure_id){
  1148. $map['structure_id'] = $structure_id;
  1149. }
  1150. $list = Db::name('AdminUser')->field('id as user_id,realname,post,structure_id')->where($map)->select();
  1151. return $list ? : [];
  1152. }
  1153. /*
  1154. *根据字符串返回数组
  1155. *
  1156. */
  1157. public function getListByStr($str)
  1158. {
  1159. $idArr = stringToArray($str);
  1160. $list = db('admin_user')->field('id,username,realname,thumb_img')->where(['id' => ['in',$idArr]])->select();
  1161. return $list;
  1162. }
  1163. /*
  1164. *读写权限
  1165. *
  1166. */
  1167. public function rwPre($user_id, $ro_user_id, $rw_user_id, $action = 'read')
  1168. {
  1169. if ($action == 'update') {
  1170. if (!in_array($user_id, stringToArray($rw_user_id))) {
  1171. return false;
  1172. }
  1173. } else {
  1174. if (!in_array($user_id, stringToArray($ro_user_id))) {
  1175. return false;
  1176. }
  1177. }
  1178. return true;
  1179. }
  1180. /**
  1181. * [getUserThree 员工第三方扩展信息]
  1182. * @param key 分类
  1183. * @author Michael_xu
  1184. * @return [array]
  1185. */
  1186. public function getUserThree($key, $user_id)
  1187. {
  1188. $resValue = db('admin_user_threeparty')->where(['key' => $key,'user_id' => $user_id])->value('value');
  1189. return $resValue ? : '';
  1190. }
  1191. /**
  1192. * 获取当前登录用户信息
  1193. *
  1194. * @param string $key 默认返回所有信息
  1195. * @return mixed
  1196. * @author Ymob
  1197. * @datetime 2019-10-22 14:38:07
  1198. */
  1199. public static function userInfo($key = '')
  1200. {
  1201. $request = Request::instance();
  1202. $header = $request->header();
  1203. $authKey = $header['authkey'];
  1204. $sessionId = $header['sessionid'];
  1205. $paramArr = $request->param();
  1206. $platform = $paramArr['platform'] ? '_' . $paramArr['platform'] : ''; //请求平台(mobile,ding)
  1207. $cache = cache('Auth_' . $authKey . $platform);
  1208. if ($cache) {
  1209. if ($key) {
  1210. return $cache['userInfo'][$key];
  1211. } else {
  1212. return $cache['userInfo'];
  1213. }
  1214. } else {
  1215. return false;
  1216. }
  1217. }
  1218. /**
  1219. * 判断用户是否拥有 某(些) 角色
  1220. *
  1221. * @param array $group_list
  1222. * @param integer $user_id
  1223. * @return bool
  1224. * @author Ymob
  1225. * @datetime 2019-10-25 15:50:48
  1226. */
  1227. public static function checkUserGroup($group_list = [], $user_id = 0)
  1228. {
  1229. $user_id = $user_id ?: self::userInfo('id');
  1230. if (empty($group_list))
  1231. return !!Access::where(['user_id' => $user_id, 'group_id' => ['IN', $group_list]])->value('user_id');
  1232. }
  1233. /**
  1234. * 顶部菜单栏显示
  1235. * @param $param
  1236. * @return array
  1237. */
  1238. public function sortList($param){
  1239. $list=Db::name('admin_sort')->where('user_id',$param['user_id'])->field('value')->find();
  1240. $list=unserialize($list['value']);
  1241. return $list?:[];
  1242. }
  1243. /**
  1244. * 修改顶部菜单显示
  1245. * @param $param
  1246. */
  1247. public function updateSort($param){
  1248. $list=Db::name('admin_sort')->where('user_id',$param['user_id'])->field('value')->select();
  1249. if($list){
  1250. $data= Db::name('admin_sort')->where('user_id',$param['user_id'])->update(['value'=>serialize($param['value'])]);
  1251. }else{
  1252. $data= Db::name('admin_sort')->insert(['user_id'=>$param['user_id'],'value'=>serialize($param['value'])]);
  1253. }
  1254. return $data;
  1255. }
  1256. /**
  1257. * 复制员工角色
  1258. *
  1259. * @param $param
  1260. * @return bool
  1261. */
  1262. public function copyRole($param)
  1263. {
  1264. $userIds = !empty($param['user_id']) ? $param['user_id'] : [];
  1265. $structureIds = !empty($param['structure_id']) ? $param['structure_id'] : [];
  1266. $groupIds = !empty($param['group_id']) ? $param['group_id'] : [];
  1267. # 员工与角色关联数据
  1268. $userGroup = [];
  1269. # 查询部门下的员工ID
  1270. if (!empty($structureIds)) {
  1271. $userIds = Db::name('admin_user')->whereIn('structure_id', $param['structure_id'])->column('id');
  1272. $userIds = array_unique((array)$userIds);
  1273. }
  1274. Db::startTrans();
  1275. try{
  1276. # 删除员工角色关联数据
  1277. Db::name('admin_access')->whereIn('user_id', $userIds)->delete();
  1278. # 重新设置员工角色
  1279. foreach ($userIds AS $key => $value) {
  1280. # 默认跳过超级管理员
  1281. if ($value == 1) continue;
  1282. foreach ($groupIds AS $k => $v) {
  1283. $userGroup[] = [
  1284. 'user_id' => $value,
  1285. 'group_id' => $v
  1286. ];
  1287. }
  1288. }
  1289. if (!empty($userGroup)) Db::name('admin_access')->insertAll($userGroup);
  1290. Db::commit();
  1291. $user= new ApiCommon();
  1292. $user_id=$user->userInfo;
  1293. foreach ($userIds AS $key => $value) {
  1294. $userInfo=Db::name('admin_user')->where('id', $value)->find();
  1295. SystemActionLog($user_id['id'], 'admin_user','employee', $value, 'update', $userInfo['realname'], '', '','编辑员工角色:'.$userInfo['realname']);
  1296. }
  1297. return true;
  1298. } catch (\Exception $e) {
  1299. Db::rollback();
  1300. return false;
  1301. }
  1302. }
  1303. /**
  1304. * 重设部门
  1305. * @param array $ids 用户id
  1306. * @param $param 部门id
  1307. *
  1308. * @author alvin guogaobo
  1309. * @version 1.0 版本号
  1310. * @since 2021/4/24 0024 14:05
  1311. *
  1312. */
  1313. public function setUserDept($ids = [],$param)
  1314. {
  1315. if (empty($ids)) {
  1316. $this->error = '参数错误';
  1317. return false;
  1318. }
  1319. foreach ($ids as $v){
  1320. $data['id']=$v;
  1321. $data['structure_id']=$param['structure_id'];
  1322. $flag=foreachData('',$data);
  1323. }
  1324. if ($flag) {
  1325. return $flag;
  1326. } else {
  1327. $this->error ='修改失败,请稍后重试';
  1328. return false;
  1329. }
  1330. }
  1331. /**
  1332. * 员工分类总数
  1333. * @author alvin guogaobo
  1334. * @version 1.0 版本号
  1335. * @since 2021/4/24 0024 14:42
  1336. */
  1337. public function countNumOfUser(){
  1338. //全部
  1339. // $data['allUserCount']=$this->count();
  1340. // //未激活
  1341. // $data['inactiveCount']=$this->where('status',2)->count();
  1342. // //激活
  1343. // $data['activateCount']=$this->where('status',1)->count();
  1344. // //停用
  1345. // $data['disableCount']=$this->where('status',0)->count();
  1346. // //新增
  1347. // $data['addNewlyCount']=$this->where('create_time','gt',strtotime('-1 week'))->count();
  1348. $time=strtotime('-1 week');
  1349. $list=db('admin_user')->field([
  1350. 'count(id) as allUserCount,
  1351. count(case status when 2 then id else null end) as inactiveCount,
  1352. count(case status when 1 then id else null end) as activateCount,
  1353. count(case status when 0 then id else null end) as disableCount,
  1354. count(case when create_time >' .$time.' then id else null end) as addNewlyCount
  1355. '
  1356. ])->select();
  1357. $data=[];
  1358. $data['list']=$list;
  1359. return $data;
  1360. }
  1361. }