User.php 58KB

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