User.php 58KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532
  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. $nameData = db('admin_user')->where('realname', 'like', '%' . $param['realname'] . '%')->column('realname');
  284. if (in_array($param['realname'], $nameData)) {
  285. for ($j = 1; $j < 100; $j++) {
  286. $name = $param['realname'] . '-' . $j;
  287. if (in_array($name, $nameData)) {
  288. continue;
  289. } else {
  290. $name = $param['realname'] . '-' . $j;
  291. break;
  292. }
  293. }
  294. $param['realname'] = $name;
  295. }
  296. // if(db('admin_user')->where('realname',$param['realname'])->find()){
  297. // $this->error = '姓名已存在';
  298. // return false;
  299. // }
  300. } else {
  301. if (empty($param['group_id']) || !is_array($param['group_id'])) {
  302. $this->error = '请至少勾选一个用户组';
  303. return false;
  304. }
  305. }
  306. $userId=$param['userId'];
  307. unset($param['userId']);
  308. // 验证
  309. $validate = validate($this->name);
  310. if (!$validate->check($param)) {
  311. $this->error = $validate->getError();
  312. return false;
  313. }
  314. if (db('admin_user')->where('username', $param['username'])->find()) {
  315. $this->error = '手机号已存在';
  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. if($param['user_id']!=1 && empty(!in_array(1,$param['id']))){
  687. $this->error = '修改失败,无修改超级管理员权限';
  688. return false;
  689. }
  690. foreach ($param['id'] as $value) {
  691. $password = '';
  692. $userInfo = db('admin_user')->where(['id' => $value])->find();
  693. $salt = substr(md5(time()), 0, 4);
  694. $temp['salt'] = $salt;
  695. $temp['password'] = $password = user_md5($param['password'], $salt, $userInfo['username']);
  696. $flag = $flag && Db::name('AdminUser')->where('id =' . $value)->update($temp);
  697. $syncData = [];
  698. $syncData['user_id'] = $value;
  699. $syncData['salt'] = $salt;
  700. $syncData['password'] = $password;
  701. $resSync = $syncModel->syncData($syncData);
  702. }
  703. if ($flag) {
  704. foreach ($param['id'] as $v) {
  705. $userInfo = db('admin_user')->where(['id' => $v])->find();
  706. # 添加记录
  707. SystemActionLog($param['user_id'], 'admin_user', 'employee', $v, 'update', $userInfo['realname'], '', '', '重置了密码:' . $userInfo['realname']);
  708. }
  709. return $flag;
  710. } else {
  711. $this->error = '修改失败,请稍后重试';
  712. return false;
  713. }
  714. }
  715. /**
  716. * 获取菜单和权限 protected
  717. *
  718. * @param $u_id
  719. * @return array
  720. * @throws \think\db\exception\DataNotFoundException
  721. * @throws \think\db\exception\ModelNotFoundException
  722. * @throws \think\exception\DbException
  723. */
  724. public function getMenuAndRule($u_id)
  725. {
  726. $menusList = [];
  727. $ruleMap = [];
  728. $adminTypes = adminGroupTypes($u_id);
  729. if (in_array(1, $adminTypes)) {
  730. $map['status'] = 1;
  731. $menusList = Db::name('admin_menu')->where($map)->order('sort asc')->select();
  732. } else {
  733. $groups = $this->get($u_id)->groups;
  734. $ruleIds = [];
  735. foreach ($groups as $k => $v) {
  736. if (stringToArray($v['rules'])) {
  737. $ruleIds = array_merge($ruleIds, stringToArray($v['rules']));
  738. }
  739. }
  740. $ruleIds = array_unique($ruleIds);
  741. $ruleMap['id'] = array('in', $ruleIds);
  742. $ruleMap['status'] = 1;
  743. }
  744. $newRuleIds = [];
  745. // 重新设置ruleIds,除去部分已删除或禁用的权限。
  746. $rules = Db::name('admin_rule')->where($ruleMap)->select();
  747. // $ruless = Db::name('admin_rule')->where($ruleMap)->where(['level'=>2,'pid'=>0])->column('name');
  748. foreach ($rules as $k => $v) {
  749. $newRuleIds[] = $v['id'];
  750. $rules[$k]['name'] = strtolower($v['name']);
  751. if ($v['name'] == 'market') {
  752. $rules[$k]['name'] = 'activityForm';
  753. }
  754. if($v['name'] == 'warehouseProduct'){
  755. $rules[$k]['name'] = 'warehouseProduct';
  756. }
  757. }
  758. // p($rules);die();
  759. //菜单管理(弃用)
  760. // $menuMap['status'] = 1;
  761. // $menuMap['rule_id'] = array('in',$newRuleIds);
  762. // $menusList = Db::name('admin_menu')->where($menuMap)->order('sort asc')->select();
  763. $ret = [];
  764. //处理菜单成树状
  765. $tree = new \com\Tree();
  766. //处理规则成树状
  767. $rulesList = $tree->list_to_tree($rules, 'id', 'pid', 'child', 0, true, array('pid'));
  768. //权限数组
  769. $authList = rulesListToArray($rulesList, $newRuleIds);
  770. //应用控制
  771. $adminConfig = db('admin_config')->where(['pid' => 0, 'status' => 1])->column('module');
  772. $adminConfig = $adminConfig ? array_merge($adminConfig, ['bi', 'admin']) : ['bi', 'admin'];
  773. # 通讯录
  774. if (in_array('book', $adminConfig) && !empty($authList['oa']['addresslist']['index'])) {
  775. $authList['oa']['book']['index'] = true;
  776. }
  777. # 商业智能权限细化
  778. if ($authList['bi']) {
  779. if (!in_array('taskExamine', $adminConfig) && !in_array('crm', $adminConfig)) {
  780. unset($authList['bi']);
  781. } else {
  782. foreach ($authList['bi'] as $key => $val) {
  783. if (!in_array('taskExamine', $adminConfig)) {
  784. unset($authList['bi']['oa']);
  785. }
  786. if (!in_array('crm', $adminConfig)) {
  787. unset($authList['bi']['customer']);
  788. unset($authList['bi']['business']);
  789. unset($authList['bi']['product']);
  790. unset($authList['bi']['achievement']);
  791. unset($authList['bi']['contract']);
  792. unset($authList['bi']['portrait']);
  793. unset($authList['bi']['ranking']);
  794. }
  795. }
  796. }
  797. } else {
  798. unset($authList['bi']);
  799. }
  800. # 任务审批
  801. if (in_array('taskExamine', $adminConfig)) {
  802. $authList['oa']['taskExamine'] = (object)[];
  803. }
  804. # 项目
  805. if (in_array('work', $adminConfig)) {
  806. $authList['project']['projectLabelManage']['projectLabelAdd'] = !empty($authList['work']['work']['save']);
  807. $authList['project']['projectLabelManage']['projectLabelDelete'] = !empty($authList['work']['work']['save']);
  808. $authList['project']['projectLabelManage']['projectLabelUpdate'] = !empty($authList['work']['work']['save']);
  809. $authList['project']['projectManage']['save'] = !empty($authList['work']['work']['save']);
  810. }
  811. # 日志
  812. if (in_array('log', $adminConfig)) {
  813. $authList['oa']['log'] = (object)[];
  814. }
  815. # 日历
  816. if (in_array('calendar', $adminConfig)) {
  817. $authList['oa']['calendar'] = (object)[];
  818. }
  819. # 进销存
  820. // if (in_array('jxc', $adminConfig)) {
  821. // $authList['jxc']['field'] = (object)[];
  822. // $authList['jxc']['params'] = (object)[];
  823. // }
  824. # 公海权限
  825. $structureId = db('admin_user')->where('id', $u_id)->value('structure_id');
  826. $poolStatus = db('crm_customer_pool')->where('status', 1)->where(function ($requery) use ($u_id, $structureId, $adminTypes) {
  827. if (!in_array(1, $adminTypes)) $requery->whereLike('admin_user_ids', '%,' . $u_id . ',%');
  828. if (!in_array(1, $adminTypes)) $requery->whereOr('user_ids', 'like', '%,' . $u_id . ',%');
  829. if (!in_array(1, $adminTypes)) $requery->whereOr('department_ids', 'like', '%,' . $structureId . ',%');
  830. })->value('pool_id');
  831. if (!empty($poolStatus)) $authList['crm']['pool'] = ['index' => true];
  832. $ret['authList'] = $this->resetAuthorityFiled($authList);
  833. $res['manage'] = $rules;
  834. return $ret;
  835. }
  836. /**
  837. * todo 应前端要求修改部分权限字段,与java的权限字段保持一致。
  838. *
  839. * @param $authList
  840. * @return mixed
  841. */
  842. private function resetAuthorityFiled($authList)
  843. {
  844. # 客户
  845. if (isset($authList['crm']['customer']['deal_status'])) {
  846. $authList['crm']['customer']['dealStatus'] = $authList['crm']['customer']['deal_status'];
  847. unset($authList['crm']['customer']['deal_status']);
  848. }
  849. if (isset($authList['crm']['customer']['nearby'])) {
  850. $authList['crm']['customer']['nearbyCustomer'] = $authList['crm']['customer']['nearby'];
  851. unset($authList['crm']['customer']['nearby']);
  852. }
  853. # 公海权限
  854. $authList['crm']['customer']['pool'] = !empty($authList['crm']['pool']['index']);;
  855. # 跟进记录
  856. $authList['crm']['followRecord'] = $authList['crm']['activity'];
  857. # 合同
  858. if (isset($authList['crm']['contract']['discard'])) {
  859. $authList['crm']['contract']['discard'] = false;
  860. }
  861. # 发票
  862. if (isset($authList['crm']['invoice']['setinvoice'])) {
  863. $authList['crm']['invoice']['updateInvoiceStatus'] = $authList['crm']['invoice']['setinvoice'];
  864. $authList['crm']['invoice']['resetInvoiceStatus'] = $authList['crm']['invoice']['resetinvoicestatus'];
  865. unset($authList['crm']['invoice']['resetinvoicestatus']);
  866. }
  867. # 市场活动
  868. if (isset($authList['crm']['marketing']['updatestatus'])) {
  869. $authList['crm']['marketing']['updateStatus'] = $authList['crm']['marketing']['updatestatus'];
  870. unset($authList['crm']['marketing']['updatestatus']);
  871. }
  872. # 发票抬头权限
  873. if (!empty($authList['crm']['invoice']['index'])) {
  874. $authList['crm']['invoiceTitle']['index'] = true;
  875. }
  876. unset($authList['work']['work']);
  877. unset($authList['work']['task']);
  878. unset($authList['work']['taskclass']);
  879. # admin:system
  880. if (!empty($authList['admin']['system']['index'])) {
  881. $authList['admin']['system']['read'] = $authList['admin']['system']['index'];
  882. unset($authList['admin']['system']['index']);
  883. }
  884. if (!empty($authList['admin']['system']['save'])) {
  885. $authList['admin']['system']['update'] = $authList['admin']['system']['save'];
  886. }
  887. # admin:configSet
  888. if (!empty($authList['admin']['configset']['index'])) {
  889. $authList['admin']['configSet']['read'] = $authList['admin']['configset']['index'];
  890. }
  891. if (!empty($authList['admin']['configset']['update'])) {
  892. $authList['admin']['configSet']['update'] = $authList['admin']['configset']['update'];
  893. }
  894. unset($authList['admin']['configset']);
  895. # admin:users
  896. if (!empty($authList['admin']['users']['index'])) {
  897. $authList['admin']['users']['read'] = $authList['admin']['users']['index'];
  898. unset($authList['admin']['users']['index']);
  899. }
  900. if (!empty($authList['admin']['users']['enables'])) {
  901. $authList['admin']['users']['userEnables'] = $authList['admin']['users']['enables'];
  902. unset($authList['admin']['users']['enables']);
  903. }
  904. if (!empty($authList['admin']['users']['save'])) {
  905. $authList['admin']['users']['userSave'] = $authList['admin']['users']['save'];
  906. unset($authList['admin']['users']['save']);
  907. }
  908. if (!empty($authList['admin']['users']['update'])) {
  909. $authList['admin']['users']['userUpdate'] = $authList['admin']['users']['update'];
  910. unset($authList['admin']['users']['update']);
  911. }
  912. if (!empty($authList['admin']['users']['structures_save'])) {
  913. $authList['admin']['users']['deptSave'] = $authList['admin']['users']['structures_save'];
  914. unset($authList['admin']['users']['structures_save']);
  915. }
  916. if (!empty($authList['admin']['users']['structures_update'])) {
  917. $authList['admin']['users']['deptUpdate'] = $authList['admin']['users']['structures_update'];
  918. unset($authList['admin']['users']['structures_update']);
  919. }
  920. if (!empty($authList['admin']['users']['structures_delete'])) {
  921. $authList['admin']['users']['deptDelete'] = $authList['admin']['users']['structures_delete'];
  922. unset($authList['admin']['users']['structures_delete']);
  923. }
  924. # admin:group 角色权限管理
  925. if (!empty($authList['admin']['groups'])) {
  926. $authList['admin']['permission'] = $authList['admin']['groups'];
  927. unset($authList['admin']['groups']);
  928. }
  929. # admin:examine_flow
  930. if (!empty($authList['admin']['examine_flow'])) {
  931. $authList['admin']['examineFlow'] = $authList['admin']['examine_flow'];
  932. unset($authList['admin']['examine_flow']);
  933. }
  934. # admin:printing
  935. if (!empty($authList['admin']['crm']['printing'])) {
  936. $authList['admin']['crm']['print'] = $authList['admin']['crm']['printing'];
  937. unset($authList['admin']['crm']['printing']);
  938. }
  939. # admin:work
  940. if (!empty($authList['admin']['work']['work'])) {
  941. $authList['admin']['work']['update'] = $authList['admin']['work']['work'];
  942. unset($authList['admin']['work']['work']);
  943. }
  944. # admin:log
  945. if (isset($authList['admin']['adminlog']['loginlog'])) {
  946. $authList['admin']['adminLog']['loginLog'] = $authList['admin']['adminlog']['loginlog'];
  947. unset($authList['admin']['adminlog']['loginlog']);
  948. }
  949. if (isset($authList['admin']['adminlog']['actionrecord'])) {
  950. $authList['admin']['adminLog']['actionRecord'] = $authList['admin']['adminlog']['actionrecord'];
  951. unset($authList['admin']['adminlog']['actionrecord']);
  952. }
  953. if (isset($authList['admin']['adminlog']['systemlog'])) {
  954. $authList['admin']['adminLog']['systemLog'] = $authList['admin']['adminlog']['systemlog'];
  955. unset($authList['admin']['adminlog']['systemlog']);
  956. }
  957. unset($authList['admin']['adminlog']);
  958. # admin:initialize
  959. if (!empty($authList['admin']['initialize'])) {
  960. $authList['admin']['init']['initData'] = $authList['admin']['initialize']['update'];
  961. $authList['admin']['init']['index'] = $authList['admin']['initialize']['index'];
  962. unset($authList['admin']['initialize']);
  963. }
  964. # admin
  965. if (!empty($authList['admin'])) {
  966. $authList['manage'] = $authList['admin'];
  967. $adminAuth = [
  968. 'configSet.read', 'crm.achievement', 'crm.field', 'crm.pool', 'crm.setting',
  969. 'examineFlow.index', 'init.initData', 'oa.examine', 'system.read', 'users.read',
  970. 'work.update', 'permission.update'
  971. ];
  972. foreach ($authList['manage'] as $key1 => $value1) {
  973. foreach ($value1 as $key2 => $value2) {
  974. if (in_array($key1 . '.' . $key2, $adminAuth)) {
  975. $authList['manage']['other_rule'] = [
  976. 'setwelcome' => true,
  977. 'setworklogrule' => true,
  978. 'welcome' => true,
  979. 'worklogrule' => true
  980. ];
  981. }
  982. }
  983. }
  984. }
  985. if (empty($authList['manage']['other_rule'])) unset($authList['manage']);
  986. unset($authList['admin']);
  987. # 通讯录
  988. $authList['email'] = (object)[];
  989. $authList['hrm'] = (object)[];
  990. // $authList['jxc'] = (object)[];
  991. # jxc
  992. // $authList['manage']['jxc']['field'] = true;
  993. // $authList['manage']['jxc']['params'] = true;
  994. $authList['knowledge'] = (object)[];
  995. return $authList;
  996. }
  997. /**
  998. * 获取权限结构数组
  999. * @param
  1000. */
  1001. public function getRulesList($uid)
  1002. {
  1003. $ruleMap = [];
  1004. $adminTypes = adminGroupTypes($uid);
  1005. if (in_array(1, $adminTypes)) {
  1006. $map['status'] = 1;
  1007. } else {
  1008. $groups = $this->get($uid)->groups;
  1009. $ruleIds = [];
  1010. foreach ($groups as $k => $v) {
  1011. if (stringToArray($v['rules'])) {
  1012. $ruleIds = array_merge($ruleIds, stringToArray($v['rules']));
  1013. }
  1014. }
  1015. $ruleIds = array_unique($ruleIds);
  1016. $ruleMap['id'] = array('in', $ruleIds);
  1017. $ruleMap['status'] = 1;
  1018. }
  1019. $newRuleIds = [];
  1020. // 重新设置ruleIds,除去部分已删除或禁用的权限。
  1021. $rules = Db::name('admin_rule')->where($ruleMap)->select();
  1022. foreach ($rules as $k => $v) {
  1023. $newRuleIds[] = $v['id'];
  1024. $rules[$k]['name'] = strtolower($v['name']);
  1025. }
  1026. //处理规则成树状
  1027. $tree = new \com\Tree();
  1028. $rulesList = $tree->list_to_tree($rules, 'id', 'pid', 'child', 0, true, array('pid'));
  1029. $rulesList = rulesDeal($rulesList);
  1030. return $rulesList ?: [];
  1031. }
  1032. /**
  1033. * 获取用户所属角色(用户组)
  1034. * @param
  1035. */
  1036. public function getGroupTypeByAction($uid, $m, $c, $a)
  1037. {
  1038. //根据$m,$c,$a 获取对应的$a 的rule_id
  1039. $rulesList = $this->getRulesList($uid);
  1040. if (!in_array($m . '-' . $c . '-' . $a, $rulesList)) {
  1041. return false;
  1042. }
  1043. $mRuleId = db('admin_rule')->where(['name' => $m, 'level' => 1])->value('id');
  1044. $cRuleId = db('admin_rule')->where(['name' => $c, 'level' => 2, 'pid' => $mRuleId])->value('id');
  1045. $aRuleId = db('admin_rule')->where(['name' => $a, 'level' => 3, 'pid' => $cRuleId])->value('id');
  1046. //获取用户组
  1047. $groups = $this->get($uid)->groups;
  1048. if (!$groups) {
  1049. return false;
  1050. }
  1051. $groupTypes = [];
  1052. foreach ($groups as $g) {
  1053. if (in_array($aRuleId, explode(',', trim($g['rules'], ',')))) {
  1054. $groupTypes[] = $g['type'];
  1055. }
  1056. }
  1057. return $groupTypes ?: [];
  1058. }
  1059. /**
  1060. * 获取有此权限的角色
  1061. * @param
  1062. */
  1063. public function getAllUserByAction($m, $c, $a)
  1064. {
  1065. $mRuleId = db('admin_rule')->where(['name' => $m, 'level' => 1])->value('id');
  1066. $cRuleId = db('admin_rule')->where(['name' => $c, 'level' => 2, 'pid' => $mRuleId])->value('id');
  1067. $aRuleId = db('admin_rule')->where(['name' => $a, 'level' => 3, 'pid' => $cRuleId])->value('id');
  1068. $groups = db('admin_group')->where(['rules' => ['in', $aRuleId]])->column('id');
  1069. $userIds = db('admin_access')->where(['group_id' => ['in', $groups]])->column('user_id');
  1070. if (!$userIds) {
  1071. //查询管理员
  1072. $userIds = db('admin_user')->where(['id' => 1])->column('id');
  1073. }
  1074. return $userIds;
  1075. }
  1076. /**
  1077. * 根据部门获取部门的userId
  1078. * @param $strId 部门ID
  1079. * @param $type 2时包含所有下属部门
  1080. */
  1081. public function getSubUserByStr($structure_id, $type = 1)
  1082. {
  1083. // p($structure_id);die;
  1084. $allStrIds = (array)$structure_id;
  1085. if ($type == 2) {
  1086. $structureModel = new \app\admin\model\Structure();
  1087. foreach ($allStrIds as $v) {
  1088. $allSubStrIds = [];
  1089. $allSubStrIds = $structureModel->getAllChild($v);
  1090. if ($allSubStrIds) {
  1091. $allStrIds = array_merge($allStrIds, $allSubStrIds); //全部关联部门(包含下属部门)
  1092. }
  1093. }
  1094. }
  1095. $userIds = db('admin_user')->where(['structure_id' => ['in', $allStrIds]])->column('id');
  1096. return $userIds ?: [];
  1097. }
  1098. /**
  1099. * [getUserById 根据主键获取详情]
  1100. * @param
  1101. * @return
  1102. */
  1103. public function getUserById($id = '')
  1104. {
  1105. $data = Db::name('AdminUser')
  1106. ->alias('user')
  1107. ->join('__ADMIN_STRUCTURE__ structure', 'structure.id = user.structure_id', 'LEFT')
  1108. ->where(['user.id' => $id])
  1109. ->field([
  1110. 'user.id',
  1111. 'username',
  1112. 'img',
  1113. 'thumb_img',
  1114. 'realname',
  1115. 'parent_id',
  1116. 'structure.name' => 'structure_name',
  1117. 'structure.id' => 'structure_id'
  1118. ])
  1119. // ->cache('user_info' . $id, null, 'user_info')
  1120. ->find();
  1121. $data['img'] = $data['img'] ? getFullPath($data['img']) : '';
  1122. $data['thumb_img'] = $data['thumb_img'] ? getFullPath($data['thumb_img']) : '';
  1123. return $data ?: [];
  1124. }
  1125. /**
  1126. * [getUserNameById 根据主键获取详情]
  1127. * @param
  1128. * @return
  1129. */
  1130. public function getUserNameById($id = '')
  1131. {
  1132. $data = $this->where(['id' => $id])->value('realname');
  1133. return $data ?: '查看详情';
  1134. }
  1135. /**
  1136. * [getUserNameByArr 根据主键获取详情]
  1137. * @param
  1138. * @return
  1139. */
  1140. public function getUserNameByArr($ids = [])
  1141. {
  1142. if (!is_array($ids)) {
  1143. $idArr[] = $ids;
  1144. } else {
  1145. $idArr = $ids;
  1146. }
  1147. $data = $this->where(['id' => array('in', $idArr)])->column('realname');
  1148. return $data ?: [];
  1149. }
  1150. /**
  1151. * [getAdminId 获取管理员ID]
  1152. * @param
  1153. * @return
  1154. */
  1155. public function getAdminId()
  1156. {
  1157. $adminGroupUser = db('admin_access')->where(['group_id' => 1])->column('user_id');
  1158. $userIDs = $adminGroupUser ? array_merge($adminGroupUser, [1]) : [1];
  1159. return $userIDs ?: [1];
  1160. }
  1161. /**
  1162. * [getUserByIdArr 根据ID数组获取列表]
  1163. * @param
  1164. * @return
  1165. */
  1166. public function getUserByIdArr($ids = [])
  1167. {
  1168. $list = $this
  1169. ->alias('user')
  1170. ->join('__ADMIN_STRUCTURE__ structure', 'structure.id = user.structure_id', 'LEFT')
  1171. ->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();
  1172. return $list ?: [];
  1173. }
  1174. /**
  1175. * [getUserByPer 获取权限范围的user_id]
  1176. * @param
  1177. * @return
  1178. */
  1179. public function getUserByPer($m = '', $c = '', $a = '')
  1180. {
  1181. $request = Request::instance();
  1182. $header = $request->header();
  1183. $authKey = $header['authkey'];
  1184. $m = $m ? strtolower($m) : strtolower($request->module());
  1185. $c = $c ? strtolower($c) : strtolower($request->controller());
  1186. $a = $a ? strtolower($a) : strtolower($request->action());
  1187. $cache = cache('Auth_' . $authKey);
  1188. if (!$cache) {
  1189. return false;
  1190. }
  1191. $userInfo = $cache['userInfo'];
  1192. //用户所属用户组类别(数组)
  1193. $groupTypes = $this->getGroupTypeByAction($userInfo['id'], $m, $c, $a);
  1194. //数组去重
  1195. $groupTypes = $groupTypes ? array_unique($groupTypes) : [];
  1196. //用户组类别(1本人,2本人及下属,3本部门,4本部门及下属部门,5全部)
  1197. $adminIds = $this->getAdminId();
  1198. $userIds = [];
  1199. if (in_array($userInfo['id'], $adminIds)) {
  1200. $userIds = getSubUserId(true, 1);
  1201. } else {
  1202. if (!$groupTypes) {
  1203. return [];
  1204. }
  1205. if (in_array(5, $groupTypes)) {
  1206. $userIds = getSubUserId(true, 1);
  1207. } else {
  1208. foreach ($groupTypes as $v) {
  1209. if ($v == 1) {
  1210. $userIds = [$userInfo['id']];
  1211. } elseif ($v == 2) {
  1212. $userIds = getSubUserId();
  1213. } elseif ($v == 3) {
  1214. $userIds = $this->getSubUserByStr($userInfo['structure_id']);
  1215. } elseif ($v == 4) {
  1216. $userIds = $this->getSubUserByStr($userInfo['structure_id'], 2);
  1217. }
  1218. }
  1219. }
  1220. }
  1221. return $userIds ?: [];
  1222. }
  1223. /*
  1224. *根据部门ID获取员工列表
  1225. *
  1226. */
  1227. public function getUserListByStructureId($structure_id = '')
  1228. {
  1229. $map = array();
  1230. if ($structure_id) {
  1231. $map['structure_id'] = $structure_id;
  1232. }
  1233. $list = Db::name('AdminUser')->field('id as user_id,realname,post,structure_id')->where($map)->select();
  1234. return $list ?: [];
  1235. }
  1236. /*
  1237. *根据字符串返回数组
  1238. *
  1239. */
  1240. public function getListByStr($str)
  1241. {
  1242. $idArr = stringToArray($str);
  1243. $list = db('admin_user')->field('id,username,realname,thumb_img')->where(['id' => ['in', $idArr]])->select();
  1244. return $list;
  1245. }
  1246. /*
  1247. *读写权限
  1248. *
  1249. */
  1250. public function rwPre($user_id, $ro_user_id, $rw_user_id, $action = 'read')
  1251. {
  1252. if ($action == 'update') {
  1253. if (!in_array($user_id, stringToArray($rw_user_id))) {
  1254. return false;
  1255. }
  1256. } else {
  1257. if (!in_array($user_id, stringToArray($ro_user_id))) {
  1258. return false;
  1259. }
  1260. }
  1261. return true;
  1262. }
  1263. /**
  1264. * [getUserThree 员工第三方扩展信息]
  1265. * @param key 分类
  1266. * @return [array]
  1267. * @author Michael_xu
  1268. */
  1269. public function getUserThree($key, $user_id)
  1270. {
  1271. $resValue = db('admin_user_threeparty')->where(['key' => $key, 'user_id' => $user_id])->value('value');
  1272. return $resValue ?: '';
  1273. }
  1274. /**
  1275. * 获取当前登录用户信息
  1276. *
  1277. * @param string $key 默认返回所有信息
  1278. * @return mixed
  1279. * @author Ymob
  1280. * @datetime 2019-10-22 14:38:07
  1281. */
  1282. public static function userInfo($key = '')
  1283. {
  1284. $request = Request::instance();
  1285. $header = $request->header();
  1286. $authKey = $header['authkey'];
  1287. $sessionId = $header['sessionid'];
  1288. $paramArr = $request->param();
  1289. $platform = $paramArr['platform'] ? '_' . $paramArr['platform'] : ''; //请求平台(mobile,ding)
  1290. $cache = cache('Auth_' . $authKey . $platform);
  1291. if ($cache) {
  1292. if ($key) {
  1293. return $cache['userInfo'][$key];
  1294. } else {
  1295. return $cache['userInfo'];
  1296. }
  1297. } else {
  1298. return false;
  1299. }
  1300. }
  1301. /**
  1302. * 判断用户是否拥有 某(些) 角色
  1303. *
  1304. * @param array $group_list
  1305. * @param integer $user_id
  1306. * @return bool
  1307. * @author Ymob
  1308. * @datetime 2019-10-25 15:50:48
  1309. */
  1310. public static function checkUserGroup($group_list = [], $user_id = 0)
  1311. {
  1312. $user_id = $user_id ?: self::userInfo('id');
  1313. if (empty($group_list))
  1314. return !!Access::where(['user_id' => $user_id, 'group_id' => ['IN', $group_list]])->value('user_id');
  1315. }
  1316. /**
  1317. * 顶部菜单栏显示
  1318. * @param $param
  1319. * @return array
  1320. */
  1321. public function sortList($param)
  1322. {
  1323. $list = Db::name('admin_sort')->where('user_id', $param['user_id'])->field('value')->find();
  1324. $list = unserialize($list['value']);
  1325. return $list ?: [];
  1326. }
  1327. /**
  1328. * 修改顶部菜单显示
  1329. * @param $param
  1330. */
  1331. public function updateSort($param)
  1332. {
  1333. $list = Db::name('admin_sort')->where('user_id', $param['user_id'])->field('value')->select();
  1334. if ($list) {
  1335. $data = Db::name('admin_sort')->where('user_id', $param['user_id'])->update(['value' => serialize($param['value'])]);
  1336. } else {
  1337. $data = Db::name('admin_sort')->insert(['user_id' => $param['user_id'], 'value' => serialize($param['value'])]);
  1338. }
  1339. return $data;
  1340. }
  1341. /**
  1342. * 复制员工角色
  1343. *
  1344. * @param $param
  1345. * @return bool
  1346. */
  1347. public function copyRole($param)
  1348. {
  1349. $userIds = !empty($param['user_id']) ? $param['user_id'] : [];
  1350. $structureIds = !empty($param['structure_id']) ? $param['structure_id'] : [];
  1351. $groupIds = !empty($param['group_id']) ? $param['group_id'] : [];
  1352. if($param['userId']!=1 && empty(!in_array(1,$userIds))){
  1353. $this->error = '修改失败,无复制超级管理员权限';
  1354. return false;
  1355. }
  1356. # 员工与角色关联数据
  1357. $userGroup = [];
  1358. # 查询部门下的员工ID
  1359. if (!empty($structureIds)) {
  1360. $userIds = Db::name('admin_user')->whereIn('structure_id', $param['structure_id'])->column('id');
  1361. $userIds = array_unique((array)$userIds);
  1362. }
  1363. Db::startTrans();
  1364. try {
  1365. # 删除员工角色关联数据
  1366. Db::name('admin_access')->whereIn('user_id', $userIds)->delete();
  1367. # 重新设置员工角色
  1368. foreach ($userIds as $key => $value) {
  1369. # 默认跳过超级管理员
  1370. if ($value == 1) continue;
  1371. foreach ($groupIds as $k => $v) {
  1372. $userGroup[] = [
  1373. 'user_id' => $value,
  1374. 'group_id' => $v
  1375. ];
  1376. }
  1377. }
  1378. if (!empty($userGroup)) Db::name('admin_access')->insertAll($userGroup);
  1379. Db::commit();
  1380. foreach ($userIds as $key => $value) {
  1381. $userInfo = Db::name('admin_user')->where('id', $value)->find();
  1382. SystemActionLog($param['userId'], 'admin_user', 'employee', $value, 'update', $userInfo['realname'], '', '', '编辑员工角色:' . $userInfo['realname']);
  1383. }
  1384. return true;
  1385. } catch (\Exception $e) {
  1386. Db::rollback();
  1387. return false;
  1388. }
  1389. }
  1390. /**
  1391. * 重设部门
  1392. * @param array $ids 用户id
  1393. * @param $param 部门id
  1394. *
  1395. * @author alvin guogaobo
  1396. * @version 1.0 版本号
  1397. * @since 2021/4/24 0024 14:05
  1398. *
  1399. */
  1400. public function setUserDept($ids = [], $param)
  1401. {
  1402. if (empty($ids)) {
  1403. $this->error = '参数错误';
  1404. return false;
  1405. }
  1406. $data=[];
  1407. foreach ($ids as $v) {
  1408. $res['id'] = $v;
  1409. $res['structure_id'] = $param['structure_id'];
  1410. $data[] = $res;
  1411. }
  1412. $flag=$this->isUpdate(true)->saveAll($data);
  1413. if ($flag!==false) {
  1414. return 1;
  1415. } else {
  1416. $this->error = '修改失败,请稍后重试';
  1417. return false;
  1418. }
  1419. }
  1420. /**
  1421. * 员工分类总数
  1422. * @author alvin guogaobo
  1423. * @version 1.0 版本号
  1424. * @since 2021/4/24 0024 14:42
  1425. */
  1426. public function countNumOfUser()
  1427. {
  1428. //全部
  1429. // $data['allUserCount']=$this->count();
  1430. // //未激活
  1431. // $data['inactiveCount']=$this->where('status',2)->count();
  1432. // //激活
  1433. // $data['activateCount']=$this->where('status',1)->count();
  1434. // //停用
  1435. // $data['disableCount']=$this->where('status',0)->count();
  1436. // //新增
  1437. // $data['addNewlyCount']=$this->where('create_time','gt',strtotime('-1 week'))->count();
  1438. $time = strtotime('-1 week');
  1439. $list = db('admin_user')->field([
  1440. 'count(id) as allUserCount,
  1441. count(case status when 2 then id else null end) as inactiveCount,
  1442. count(case status when 1 then id else null end) as activateCount,
  1443. count(case status when 0 then id else null end) as disableCount,
  1444. count(case when create_time >' . $time . ' then id else null end) as addNewlyCount
  1445. '
  1446. ])->select();
  1447. $data = [];
  1448. $data['list'] = $list;
  1449. return $data;
  1450. }
  1451. }