User.php 56KB

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