Admin.php 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  1. <?php
  2. namespace app\admin\controller\department;
  3. use app\admin\model\department\Department;
  4. use app\admin\model\department\Department as DepartmentModel;
  5. use app\common\controller\Backend;
  6. use \app\admin\model\department\Admin as DepartmentAdminModel;
  7. use \app\admin\model\department\AuthAdmin as AdminModel;
  8. use fast\Random;
  9. use fast\Tree;
  10. use think\Db;
  11. use think\Model;
  12. use think\Validate;
  13. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  14. use PhpOffice\PhpSpreadsheet\IOFactory;
  15. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  16. use PhpOffice\PhpSpreadsheet\Reader\Csv;
  17. use PhpOffice\PhpSpreadsheet\Reader\Xls;
  18. use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
  19. /**
  20. * 部门成员
  21. */
  22. class Admin extends Backend
  23. {
  24. protected $tree = null;
  25. /**
  26. * 部门人员对象
  27. * @var null
  28. */
  29. protected $dadminModel = null;
  30. protected $childrenGroupIds = [];//权限组
  31. /**
  32. * 部门所有
  33. * @var array
  34. */
  35. protected $allDepartment = [];//
  36. protected $noNeedRight=['selectpage','getDepartmentIds','departadmintotal','export','import'];
  37. public function _initialize()
  38. {
  39. parent::_initialize();
  40. $this->childrenGroupIds = $this->auth->getChildrenGroupIds($this->auth->isSuperAdmin());
  41. $this->dadminModel = new DepartmentAdminModel;
  42. $departmentList = [];
  43. // $this->allDepartment = \app\admin\model\department\Admin::getAllDepartmentsArray($this->auth->id,($this->auth->isSuperAdmin()||$this->auth->data_scope)?true:false);
  44. $this->allDepartment = \app\admin\model\department\Admin::getAllDepartmentsArray($this->auth->id,true);
  45. $this->allDepartment=collection($this->allDepartment)->toArray();
  46. $departmentdata = [];
  47. foreach ($this->allDepartment as $k => $v) {
  48. $state = ['opened' => true];
  49. $departmentList[] = [
  50. 'id' => $v['id'],
  51. 'parent' => $v['parent_id'] ? $v['parent_id'] : '#',
  52. 'text' =>preg_replace('/&nbsp;|\s*|│|└|├\s*/','',__($v['name'])),//str_replace("&nbsp;",'', __($v['name'])) ,
  53. 'state' => $state
  54. ];
  55. }
  56. $tree = Tree::instance()->init($this->allDepartment, 'parent_id');
  57. $departmentOptions = $tree->getTree(0, "<option model='@model_id' value=@id @selected @disabled>@spacer@name</option>");
  58. $this->view->assign('departmentOptions', $departmentOptions);
  59. $this->assignconfig('departmentList', $departmentList);
  60. $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
  61. foreach ($result as $k => $v) {
  62. $departmentdata[$v['id']] = $v['name'];
  63. }
  64. $this->view->assign('departmentdata', $departmentdata);
  65. //兼容旧版本没有手机号
  66. $database=config('database');
  67. $exits_mobile=\think\Db::query("SELECT 1 FROM information_schema.COLUMNS WHERE table_name='{$database['prefix']}admin' AND COLUMN_NAME='mobile' limit 1");
  68. $this->view->assign('exits_mobile', $exits_mobile?1:0);
  69. $this->assignconfig('exits_mobile', $exits_mobile?1:0);
  70. }
  71. /**
  72. * 成员列表
  73. */
  74. public function index()
  75. {
  76. //设置过滤方法
  77. $this->request->filter(['strip_tags']);
  78. $department_id = $this->request->request("department_id");
  79. if ($this->request->isAjax()) {
  80. $this->model = new \app\admin\model\department\AuthAdmin();
  81. $filter = $this->request->get("filter", '');
  82. $filter = (array)json_decode($filter, true);
  83. $filter_w = [];
  84. $authGroupList = \app\admin\model\AuthGroupAccess::field('uid,group_id')
  85. ->where('group_id', 'in', 8)
  86. ->select();
  87. foreach ($authGroupList as $k => $v) {
  88. $childrenAdminIds[] = $v['uid'];
  89. }
  90. $filter_w['id']=['in',$childrenAdminIds];
  91. if (isset($filter['department_id'])) {
  92. $department_id = $filter['department_id'];
  93. unset($filter['department_id']);
  94. $this->request->get(['filter' => json_encode($filter)]);
  95. }
  96. if ($department_id) {
  97. if (!in_array($department_id,array_column($this->allDepartment,'id'))){
  98. $this->error("您所选的部门没有权限");
  99. }
  100. $admin_ids = $this->dadminModel->where('department_id', 'in', $department_id)->column('admin_id');
  101. $filter_w['id'] = ['in', $admin_ids];
  102. }
  103. // else if ($this->auth->data_scope!=1&&!$this->auth->isSuperAdmin()){
  104. // $this->childrenAdminIds = \app\admin\model\department\Admin::getChildrenAdminIds($this->auth->id, true);
  105. // $filter_w['admin_id']=['in',$this->childrenAdminIds];
  106. // }
  107. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  108. $total = $this->model
  109. ->where($where)
  110. ->where($filter_w)
  111. ->order($sort, $order)->fetchSql(false)
  112. ->count();
  113. $list = $this->model
  114. ->where($where)
  115. ->with(['dadmin.department'])
  116. ->with(['groups.getGroup'])
  117. ->where($filter_w)
  118. ->order($sort, $order)
  119. ->limit($offset, $limit)->fetchSql(false)
  120. ->select();
  121. $result = array("total" => $total, "rows" => $list);
  122. return json($result);
  123. }
  124. return $this->view->fetch();
  125. }
  126. /**
  127. * 添加
  128. * @return string|\think\response\Json
  129. * @throws \think\Exception
  130. * @throws \think\db\exception\DataNotFoundException
  131. * @throws \think\db\exception\ModelNotFoundException
  132. * @throws \think\exception\DbException
  133. */
  134. public function add()
  135. {
  136. $groupdata = DepartmentModel::getGroupdata(
  137. $this->childrenGroupIds,
  138. $this->auth->isSuperAdmin() ? null : $this->auth->getGroups()
  139. );
  140. if ($this->request->isPost()) {
  141. $adminModel = new AdminModel();
  142. $departmentModel = new DepartmentModel();
  143. $params = $this->request->post("row/a");
  144. if ($params) {
  145. Db::startTrans();
  146. try {
  147. $department_id = $this->request->post("department_id/a");
  148. $is_principal = $this->request->post("is_principal",'0','intval');
  149. //获取部门信息
  150. if (!$department_id) {
  151. exception(__("组织不能为空"));
  152. }
  153. $d_list = $departmentModel->where('id', 'in', $department_id)->select();
  154. if (!$d_list) {
  155. exception(__("组织不能为空"));
  156. }
  157. foreach ($d_list as $d_row){
  158. if ($d_row['level']!=5){
  159. exception(__("学员请选择到区队"));
  160. }
  161. }
  162. if (!Validate::is($params['password'], '\S{6,16}')) {
  163. exception(__("Please input correct password"));
  164. }
  165. $params['depart_id'] = $department_id[0]??0;
  166. $params['salt'] = Random::alnum();
  167. $params['password'] = md5(md5($params['password']) . $params['salt']);
  168. $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
  169. $result = $adminModel->validate('Admin.add')->save($params);
  170. if ($result === false) {
  171. exception($adminModel->getError());
  172. }
  173. if (!$this->auth->isSuperAdmin()&&isset($params['data_scope'])){
  174. unset($params['data_scope']);//超级管理人才能赋予全部数据权限
  175. }
  176. $admin_id = $adminModel->id;
  177. $dadmin = array();
  178. //添加部门信息
  179. foreach ($d_list as $d_row) {
  180. $dadmin[] = ['is_principal'=>$is_principal==1?1:0,'department_id' => $d_row->id, 'organise_id' => $d_row->organise_id ? $d_row->organise_id : $d_row->id, 'admin_id' => $admin_id];
  181. }
  182. $this->dadminModel->saveAll($dadmin);
  183. $group = $this->request->post("group/a");
  184. //过滤不允许的组别,避免越权
  185. $group = [8];//array_intersect($this->childrenGroupIds, $group);
  186. //添加权限默认
  187. if (!$group) {
  188. exception(__('The parent group exceeds permission limit'));
  189. }
  190. $dataset = [];
  191. foreach ($group as $value) {
  192. $dataset[] = ['uid' => $admin_id, 'group_id' => $value];
  193. }
  194. model('AuthGroupAccess')->saveAll($dataset);
  195. Db::commit();
  196. } catch (\Exception $e) {
  197. Db::rollback();
  198. $this->error($e->getMessage());
  199. }
  200. $this->success();
  201. }
  202. $this->error(__('Parameter %s can not be empty', ''));
  203. }
  204. $this->view->assign('groupdata', $groupdata);
  205. return $this->view->fetch();
  206. }
  207. /**
  208. * 修改
  209. * @param null $ids
  210. * @return string|\think\response\Json
  211. * @throws \think\Exception
  212. * @throws \think\db\exception\DataNotFoundException
  213. * @throws \think\db\exception\ModelNotFoundException
  214. * @throws \think\exception\DbException
  215. */
  216. public function edit($ids = null)
  217. {
  218. $this->model = new AdminModel();
  219. $departmentModel = new DepartmentModel();
  220. $row = $this->model->get($ids);
  221. if (!$row) {
  222. $this->error(__('No Results were found'));
  223. }
  224. // if (!\app\admin\model\department\Admin::checkDataAuth($this->auth,$row,'id')){
  225. // $this->error(__('You have no permission'));
  226. // }
  227. if ($this->request->isPost()) {
  228. //判断是不是超级管理员编辑
  229. // if (!$this->auth->isSuperAdmin() && DepartmentAdminModel::isSuperAdmin($row->id)) {
  230. // $this->error("您无权操作超级管理员");
  231. // }
  232. $params = $this->request->post("row/a");
  233. if ($params) {
  234. Db::startTrans();
  235. try {
  236. $department_id = $this->request->post("department_id/a");
  237. //获取部门信息
  238. if (!$department_id) {
  239. exception(__("Department can't null"));
  240. }
  241. $d_list = $departmentModel->where('id', 'in', $department_id)->select();
  242. if (!$d_list) {
  243. exception(__("Department can't null"));
  244. }
  245. foreach ($d_list as $d_row){
  246. if ($d_row['level']!=5){
  247. exception(__("学员请选择到区队"));
  248. }
  249. }
  250. if ($params['password']) {
  251. if (!Validate::is($params['password'], '\S{6,16}')) {
  252. exception(__("Please input correct password"));
  253. }
  254. $params['salt'] = Random::alnum();
  255. $params['password'] = md5(md5($params['password']) . $params['salt']);
  256. } else {
  257. unset($params['password'], $params['salt']);
  258. }
  259. if (!$this->auth->isSuperAdmin()&&isset($params['data_scope'])){
  260. unset($params['data_scope']);//超级管理人才能赋予全部数据权限
  261. }
  262. $params['depart_id'] = $department_id[0]??0;
  263. //这里需要针对username和email做唯一验证
  264. $adminValidate = \think\Loader::validate('Admin');
  265. $adminValidate->rule([
  266. 'username' => 'require|regex:\w{3,20}|unique:admin,username,' . $row->id,
  267. // 'email' => 'require|email|unique:admin,email,' . $row->id,
  268. // 'mobile' => 'regex:1[3-9]\d{9}|unique:admin,mobile,' . $row->id,
  269. 'password' => 'regex:\S{32}',
  270. ]);
  271. $result = $row->validate('Admin.edit')->save($params);
  272. if ($result === false) {
  273. exception($row->getError());
  274. }
  275. $exist_departmentids = $this->dadminModel->where('admin_id', $row->id)->column('department_id');
  276. $dadmin = array();
  277. $deleteids = array_diff($exist_departmentids, $department_id);
  278. //添加部门信息
  279. foreach ($d_list as $d_row) {
  280. if (!in_array($d_row->id, $exist_departmentids)) {
  281. $dadmin[] = ['department_id' => $d_row->id, 'organise_id' => $d_row->organise_id ? $d_row->organise_id : $d_row->id, 'admin_id' => $row->id];
  282. }
  283. }
  284. if ($deleteids) {
  285. $this->dadminModel->where('admin_id', $row->id)->where('department_id', 'in', $deleteids)->delete();
  286. }
  287. if (count($dadmin) > 0) {
  288. $this->dadminModel->saveAll($dadmin);
  289. }
  290. // 先移除所有权限
  291. model('AuthGroupAccess')->where('uid', $row->id)->delete();
  292. $group = $this->request->post("group/a");
  293. // 过滤不允许的组别,避免越权
  294. $group = [8];//array_intersect($this->childrenGroupIds, $group);
  295. if (!$group) {
  296. exception(__('The parent group exceeds permission limit'));
  297. }
  298. $dataset = [];
  299. foreach ($group as $value) {
  300. $dataset[] = ['uid' => $row->id, 'group_id' => $value];
  301. }
  302. model('AuthGroupAccess')->saveAll($dataset);
  303. Db::commit();
  304. } catch (\Exception $e) {
  305. Db::rollback();
  306. $this->error($e->getMessage());
  307. }
  308. $this->success();
  309. }
  310. $this->error(__('Parameter %s can not be empty', ''));
  311. }
  312. $groupdata = DepartmentModel::getGroupdata(
  313. $this->childrenGroupIds,
  314. $this->auth->isSuperAdmin() ? null : $this->auth->getGroups()
  315. );
  316. $grouplist = $this->auth->getGroups($row['id']);
  317. $groupids = [];
  318. foreach ($grouplist as $k => $v) {
  319. $groupids[] = $v['id'];
  320. }
  321. $this->view->assign("groupids", $groupids);
  322. $this->view->assign('row', $row);
  323. $this->view->assign('department_ids', $this->dadminModel->getDepartmentIds($ids));
  324. $this->view->assign('groupdata', $groupdata);
  325. return $this->view->fetch();
  326. }
  327. /**
  328. * 删除
  329. */
  330. public function del($ids = "")
  331. {
  332. if (!$this->request->isPost()) {
  333. $this->error(__("Invalid parameters"));
  334. }
  335. $this->childrenAdminIds = $this->auth->getChildrenAdminIds($this->auth->isSuperAdmin());
  336. $this->model = new AdminModel();
  337. $ids = $ids ? $ids : $this->request->post("ids");
  338. if ($ids) {
  339. $ids = array_intersect($this->childrenAdminIds, array_filter(explode(',', $ids)));
  340. // 避免越权删除管理员
  341. $childrenGroupIds = $this->childrenGroupIds;
  342. $adminList = $this->model->where('id', 'in', $ids)->where('id', 'in', function ($query) use ($childrenGroupIds) {
  343. $query->name('auth_group_access')->where('group_id', 'in', $childrenGroupIds)->field('uid');
  344. })->select();
  345. if ($adminList) {
  346. $deleteIds = [];
  347. foreach ($adminList as $k => $v) {
  348. $deleteIds[] = $v->id;
  349. }
  350. $deleteIds = array_values(array_diff($deleteIds, [$this->auth->id]));
  351. if ($deleteIds) {
  352. Db::startTrans();
  353. try {
  354. $this->model->destroy($deleteIds);
  355. model('AuthGroupAccess')->where('uid', 'in', $deleteIds)->delete();
  356. //删除部门员工信息
  357. $this->dadminModel->where('admin_id', 'in', $deleteIds)->delete();;
  358. Db::commit();
  359. } catch (\Exception $e) {
  360. Db::rollback();
  361. $this->error($e->getMessage());
  362. }
  363. $this->success();
  364. }
  365. $this->error(__('No rows were deleted'));
  366. }
  367. }
  368. $this->error(__('You have no permission'));
  369. }
  370. /**
  371. * 批量更新
  372. */
  373. public function multi($ids = "")
  374. {
  375. $this->model = new AdminModel();
  376. return parent::multi($ids);
  377. }
  378. /**
  379. * 设置部门负责人
  380. */
  381. public function principal($ids = "")
  382. {
  383. $this->model = new AdminModel();
  384. $departmentModel = new DepartmentModel();
  385. $row = $this->model->get($ids);
  386. if ($this->request->isPost()) {
  387. //判断是不是超级管理员编辑
  388. if (!DepartmentAdminModel::isSuperAdmin($this->auth->id) && DepartmentAdminModel::isSuperAdmin($row->id)) {
  389. $this->error("您无权操作超级管理员");
  390. }
  391. $department_id = $this->request->post("department_id/a");
  392. if ($department_id && $department_id[0]) {
  393. Db::startTrans();
  394. try {
  395. $d_list = $departmentModel->where('id', 'in', $department_id)->select();
  396. if (!$d_list) {
  397. exception(__("Department can't null"));
  398. }
  399. //先移除他所有负责的部门
  400. $this->dadminModel->where('admin_id', $row->id)->update(['is_principal' => 0]);
  401. //判断选择的部门是否存在,不存在就先把他加入
  402. $p_departmentids = array_column($d_list, 'id');
  403. $exist_departmentids = $this->dadminModel->where('admin_id', $row->id)->column('department_id');
  404. $dadmin = array();
  405. //添加部门信息
  406. foreach ($d_list as $d_row) {
  407. if (!in_array($d_row->id, $exist_departmentids)) {
  408. $dadmin[] = ['department_id' => $d_row->id, 'organise_id' => $d_row->organise_id ? $d_row->organise_id : $d_row->id, 'admin_id' => $row->id];
  409. }
  410. }
  411. if (count($dadmin) > 0) {
  412. $this->dadminModel->saveAll($dadmin);
  413. }
  414. //更改为负责人
  415. $this->dadminModel->where('admin_id', $row->id)->where('department_id', 'in', $p_departmentids)->update(['is_principal' => 1]);
  416. Db::commit();
  417. } catch (\Exception $e) {
  418. Db::rollback();
  419. $this->error($e->getMessage());
  420. }
  421. } else {
  422. //移除他所有负责的部门
  423. $this->dadminModel->where('admin_id', $row->id)->update(['is_principal' => 0]);
  424. }
  425. $this->success();
  426. }
  427. $this->view->assign('row', $row);
  428. $this->view->assign('department_ids', $this->dadminModel::getPrincipalIds($ids));
  429. return $this->view->fetch();
  430. }
  431. /**
  432. * 获取员工的部门IDs
  433. */
  434. public function getDepartmentIds($id = ""){
  435. $departmentIds=DepartmentAdminModel::getDepartmentIds($id);
  436. //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
  437. $this->success("",'',['departmentIds' => $departmentIds]);
  438. }
  439. /**
  440. * 下拉选择
  441. * @Internal
  442. */
  443. public function selectpage()
  444. {
  445. $type=$this->request->request('type');//all代表选择所有
  446. $custom = ['status' => 'normal'];
  447. if ($type != "all") {
  448. $childrenAdminIds = \app\admin\model\department\Admin::getChildrenAdminIds($this->auth->id, true);
  449. $custom['id'] = ['in', $childrenAdminIds];
  450. }
  451. $this->selectpageFields = ['id', 'concat(nickname,"(",id,")") as nickname'];
  452. $this->request->request(['custom' => $custom]);
  453. //搜索字段
  454. $searchfield = (array)$this->request->request("searchField/a");
  455. $searchfield[]='id';
  456. $this->request->request(['searchField'=>$searchfield]);
  457. $this->model = model('admin');
  458. //设置过滤方法
  459. $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);
  460. //搜索关键词,客户端输入以空格分开,这里接收为数组
  461. $word = (array)$this->request->request("q_word/a");
  462. //当前页
  463. $page = $this->request->request("pageNumber");
  464. //分页大小
  465. $pagesize = $this->request->request("pageSize");
  466. //搜索条件
  467. $andor = $this->request->request("andOr", "and", "strtoupper");
  468. //排序方式
  469. $orderby = (array)$this->request->request("orderBy/a");
  470. //显示的字段
  471. $field = $this->request->request("showField");
  472. //主键
  473. $primarykey = $this->request->request("keyField");
  474. //主键值
  475. $primaryvalue = $this->request->request("keyValue");
  476. //搜索字段
  477. $searchfield = (array)$this->request->request("searchField/a");
  478. //自定义搜索条件
  479. $custom = (array)$this->request->request("custom/a");
  480. //是否返回树形结构
  481. $istree = $this->request->request("isTree", 0);
  482. $ishtml = $this->request->request("isHtml", 0);
  483. if ($istree) {
  484. $word = [];
  485. $pagesize = 999999;
  486. }
  487. $order = [];
  488. foreach ($orderby as $k => $v) {
  489. $order[$v[0]] = $v[1];
  490. }
  491. $field = $field ? $field : 'name';
  492. //如果有primaryvalue,说明当前是初始化传值
  493. if ($primaryvalue !== null) {
  494. $where = [$primarykey => ['in', $primaryvalue]];
  495. $pagesize = 999999;
  496. } else {
  497. $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
  498. $logic = $andor == 'AND' ? '&' : '|';
  499. $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
  500. $searchfield = str_replace(',', $logic, $searchfield);
  501. $word = array_filter(array_unique($word));
  502. if (count($word) == 1) {
  503. $query->where($searchfield, "like", "%" . reset($word) . "%");
  504. } else {
  505. $query->where(function ($query) use ($word, $searchfield) {
  506. foreach ($word as $index => $item) {
  507. $query->whereOr(function ($query) use ($item, $searchfield) {
  508. $query->where($searchfield, "like", "%{$item}%");
  509. });
  510. }
  511. });
  512. }
  513. if ($custom && is_array($custom)) {
  514. foreach ($custom as $k => $v) {
  515. if (is_array($v) && 2 == count($v)) {
  516. $query->where($k, trim($v[0]), $v[1]);
  517. } else {
  518. $query->where($k, '=', $v);
  519. }
  520. }
  521. }
  522. };
  523. }
  524. $adminIds = $this->getDataLimitAdminIds();
  525. if (is_array($adminIds)) {
  526. $this->model->where($this->dataLimitField, 'in', $adminIds);
  527. }
  528. $list = [];
  529. $total = $this->model->where($where)->count();
  530. if ($total > 0) {
  531. if (is_array($adminIds)) {
  532. $this->model->where($this->dataLimitField, 'in', $adminIds);
  533. }
  534. $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);
  535. //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
  536. if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
  537. $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
  538. //修复自定义data-primary-key为字符串内容时,给排序字段添加上引号
  539. $primaryvalue = array_map(function ($value) {
  540. return '\'' . $value . '\'';
  541. }, $primaryvalue);
  542. $primaryvalue = implode(',', $primaryvalue);
  543. $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
  544. } else {
  545. $this->model->order($order);
  546. }
  547. $datalist = $this->model->where($where)
  548. ->field($this->selectpageFields)
  549. ->page($page, $pagesize)
  550. ->select();
  551. foreach ($datalist as $index => $item) {
  552. unset($item['password'], $item['salt']);
  553. if ($this->selectpageFields == '*') {
  554. $result = [
  555. $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
  556. $field => isset($item[$field]) ? $item[$field] : '',
  557. ];
  558. } else {
  559. $result = (($item instanceof Model ? $item->toArray() : (array)$item));
  560. }
  561. $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
  562. $list[] = $result;
  563. }
  564. if ($istree && !$primaryvalue) {
  565. $tree = Tree::instance();
  566. $tree->init(collection($list)->toArray(), 'pid');
  567. $list = $tree->getTreeList($tree->getTreeArray(0), $field);
  568. if (!$ishtml) {
  569. foreach ($list as &$item) {
  570. $item = str_replace('&nbsp;', ' ', $item);
  571. }
  572. unset($item);
  573. }
  574. }
  575. }
  576. //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
  577. return json(['list' => $list, 'total' => $total]);
  578. }
  579. public function departadmintotal()
  580. {
  581. //设置过滤方法
  582. $this->request->filter(['strip_tags', 'trim']);
  583. if (false === $this->request->isAjax()) {
  584. return $this->view->fetch();
  585. }
  586. //如果发送的来源是 Selectpage,则转发到 Selectpage
  587. if ($this->request->request('keyField')) {
  588. return $this->selectpage();
  589. }
  590. [$where, $sort, $order, $offset, $limit] = $this->buildparams();
  591. $departmentModel = new DepartmentModel();
  592. $list = $departmentModel
  593. ->where($where)->where(['level'=>5])
  594. ->order($sort, $order)
  595. ->paginate($limit);
  596. foreach ($list as $k => $v){
  597. $v->department_name = '';
  598. if(!empty($v->parent_id)){
  599. $row = $departmentModel->where(['id'=>$v->parent_id])->find();
  600. if(!empty($row->parent_id)){
  601. $row2 = $departmentModel->where(['id'=>$row->parent_id])->find();
  602. if(!empty($row2->parent_id)){
  603. $row3 = $departmentModel->where(['id'=>$row2->parent_id])->find();
  604. if(!empty($row3->parent_id)) {
  605. $row4 = $departmentModel->where(['id' => $row3->parent_id])->find();
  606. $v->department_name = $row4['name'].">>".$row3['name'].">>".$row2['name'].">>".$row['name'].">>".$v['name'];
  607. }
  608. }
  609. }
  610. }
  611. $v->department_admin_count = Db::name('admin')->where(['depart_id'=>$v['id']])->count();
  612. $v->alluser = Db::name('admin')->where(['depart_id'=>$v['id']])->select();
  613. $v->user_ids = Db::name('admin')->where(['depart_id'=>$v['id']])->column('id');
  614. }
  615. unset($v);
  616. $result = ['total' => $list->total(), 'rows' => $list->items()];
  617. return json($result);
  618. }
  619. //导入
  620. public function import(){
  621. error_reporting(E_ALL);
  622. ini_set("memory_limit","8000M");
  623. $file = $this->request->request('file');
  624. if (!$file) {
  625. $this->error(__('Parameter %s can not be empty', 'file'));
  626. }
  627. $filePath = ROOT_PATH . DS . 'public' . DS . $file;
  628. if (!is_file($filePath)) {
  629. $this->error(__('No results were found'));
  630. }
  631. //实例化reader
  632. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  633. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  634. $this->error(__('Unknown data format'));
  635. }
  636. if ($ext === 'csv') {
  637. $file = fopen($filePath, 'r');
  638. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  639. $fp = fopen($filePath, "w");
  640. $n = 0;
  641. while ($line = fgets($file)) {
  642. $line = rtrim($line, "\n\r\0");
  643. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  644. if ($encoding != 'utf-8') {
  645. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  646. }
  647. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  648. fwrite($fp, $line . "\n");
  649. } else {
  650. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  651. }
  652. $n++;
  653. }
  654. fclose($file) || fclose($fp);
  655. $reader = new Csv();
  656. } elseif ($ext === 'xls') {
  657. $reader = new Xls();
  658. } else {
  659. $reader = new Xlsx();
  660. }
  661. //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
  662. $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
  663. $this->model = new \app\admin\model\department\AuthAdmin();
  664. $table = $this->model->getQuery()->getTable();
  665. $fieldArr['学号'] = 'username';
  666. $fieldArr['姓名'] = 'nickname';
  667. $fieldArr['层次'] = 'cengci';
  668. $fieldArr['专业'] = 'zhuanye';
  669. $fieldArr['年级'] = 'nianji';
  670. $fieldArr['队'] = 'dui';
  671. $fieldArr['区队'] = 'depart_id';
  672. //加载文件
  673. $insert = [];
  674. try {
  675. if (!$PHPExcel = $reader->load($filePath)) {
  676. $this->error(__('Unknown data format'));
  677. }
  678. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  679. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  680. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  681. $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  682. $fields = [];
  683. for ($currentRow = 2; $currentRow <= 2; $currentRow++) {
  684. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  685. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  686. $fields[] = $val;
  687. }
  688. }
  689. for ($currentRow = 3; $currentRow <= $allRow; $currentRow++) {
  690. $values = [];
  691. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  692. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  693. $values[] = is_null($val) ? '' : $val;
  694. }
  695. $row = [];
  696. $temp = array_combine($fields, $values);
  697. foreach ($temp as $k => $v) {
  698. if (isset($fieldArr[$k]) && $k !== '') {
  699. $row[$fieldArr[$k]] = trim($v);
  700. }
  701. }
  702. if ($row) {
  703. $insert[] = $row;
  704. }
  705. }
  706. } catch (Exception $exception) {
  707. $this->error($exception->getMessage());
  708. }
  709. if (!$insert) {
  710. $this->error(__('No rows were updated'));
  711. }
  712. $idcard_str = '';
  713. $insert_data = [];
  714. try {
  715. foreach ($insert as $key => $v)
  716. {
  717. if(!empty($v['username'])){
  718. if(empty($v['cengci'])){
  719. $idcard_str.= $v['nickname'].":层次不能为空<br/>";
  720. continue;
  721. }
  722. if(empty($v['zhuanye'])){
  723. $idcard_str.= $v['nickname'].":专业不能为空<br/>";
  724. continue;
  725. }
  726. if(empty($v['nianji'])){
  727. $idcard_str.= $v['nickname'].":年级不能为空<br/>";
  728. continue;
  729. }
  730. if(empty($v['dui'])){
  731. $idcard_str.= $v['nickname'].":队不能为空<br/>";
  732. continue;
  733. }
  734. if(empty($v['depart_id'])){
  735. $idcard_str.= $v['nickname'].":区队不能为空<br/>";
  736. continue;
  737. }
  738. //层次
  739. $cengci = Db::name('department')->where('name',$v['cengci'])->where('parent_id',0)->value('id');
  740. if(empty($cengci)){
  741. $idcard_str.= $v['nickname'].":层次有误,请核实是否存在<br/>";
  742. continue;
  743. }else{
  744. //专业
  745. $zhuanye = Db::name('department')->where('name',$v['zhuanye'])->where('parent_id',$cengci)->value('id');
  746. if(empty($zhuanye)){
  747. $idcard_str.= $v['nickname'].":专业有误,请核实是否存在或是否为层次下级<br/>";
  748. continue;
  749. }else{
  750. //年级
  751. $nianji = Db::name('department')->where('name',$v['nianji'])->where('parent_id',$zhuanye)->value('id');
  752. if(empty($nianji)){
  753. $idcard_str.= $v['nickname'].":年级有误,请核实是否存在或是否为专业下级<br/>";
  754. continue;
  755. }else{
  756. //队
  757. $dui = Db::name('department')->where('name',$v['dui'])->where('parent_id',$nianji)->value('id');
  758. if(empty($dui)){
  759. $idcard_str.= $v['nickname'].":队有误,请核实是否存在或是否为年级下级<br/>";
  760. continue;
  761. }else{
  762. //区队
  763. $depart_id = Db::name('department')->where('name',$v['depart_id'])->where('parent_id',$dui)->value('id');
  764. if(empty($depart_id)){
  765. $idcard_str.= $v['nickname'].":区队有误,请核实是否存在或是否为队下级<br/>";
  766. continue;
  767. }
  768. }
  769. }
  770. }
  771. }
  772. $admin_info = Db::name('admin')->where('username',$v['username'])->find();
  773. if(empty($admin_info)){
  774. $salt = Random::alnum();
  775. $insert = [
  776. 'username'=>$v['username'],
  777. 'nickname'=>$v['nickname'],
  778. 'salt'=>$salt,
  779. 'password'=>$this->auth->getEncryptPassword('123456', $salt),
  780. 'avatar'=>'/assets/img/avatar.png',
  781. 'loginfailure'=>0,
  782. 'email'=>$v['username'].'@163.com',
  783. 'status'=>'normal',
  784. 'createtime'=>time(),
  785. 'updatetime'=>time(),
  786. 'depart_id'=>$depart_id??0,
  787. ];
  788. $adminId = Db::name('admin')->insertGetId($insert);
  789. $add = [
  790. 'department_id'=>$depart_id??0,
  791. 'admin_id'=>$adminId,
  792. 'create_time'=>time(),
  793. 'update_time'=>time(),
  794. ];
  795. $departmentId = Db::name('department_admin')->insertGetId($add);
  796. $group_info = Db::name('auth_group_access')->where('uid',$adminId)->find();
  797. if(empty($group_info)){
  798. $arr = [
  799. 'uid'=>$adminId,
  800. 'group_id'=>8
  801. ];
  802. Db::name('auth_group_access')->insertGetId($arr);
  803. }
  804. }else{
  805. //已存在更新
  806. Db::name('admin')->where('id',$admin_info['id'])->update(['depart_id'=>$depart_id]);
  807. Db::name('department_admin')->where('admin_id',$admin_info['id'])->update(['department_id'=>$depart_id]);
  808. }
  809. }
  810. }
  811. } catch (PDOException $exception) {
  812. $msg = $exception->getMessage();
  813. if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
  814. $msg = "导入失败,包含【{$matches[1]}】的记录已存在";
  815. };
  816. $this->error($msg);
  817. } catch (Exception $e) {
  818. $this->error($e->getMessage());
  819. }
  820. if(!empty($idcard_str) ){
  821. $msg = '导入成功,';
  822. if (!empty($idcard_str)) {
  823. $msg .= '以下数据不合理:<br />' . $idcard_str;
  824. }
  825. $this->success($msg,'',[],15);
  826. }else{
  827. $this->success('导入成功');
  828. }
  829. }
  830. //导出
  831. public function export(){
  832. $this->model = new \app\admin\model\department\AuthAdmin();
  833. $filter = $this->request->get("filter", '');
  834. $filter = (array)json_decode($filter, true);
  835. $filter_w = [];
  836. if (isset($filter['department_id'])) {
  837. $department_id = $filter['department_id'];
  838. unset($filter['department_id']);
  839. $this->request->get(['filter' => json_encode($filter)]);
  840. }
  841. if ($department_id) {
  842. $filter_w['depart_id'] = ['in', $department_id];
  843. }
  844. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  845. $list = $this->model->where($where)->where(['depart_id'=>['>',0]])->where($filter_w)->order($sort, $order)->select();
  846. $xlsName = '学员信息';
  847. $this->exportExcel($xlsName,'Excel2007', $list);
  848. }
  849. /**
  850. * 输出到浏览器(需要设置header头)
  851. * @param string $fileName 文件名
  852. * @param string $fileType 文件类型
  853. */
  854. function exportExcel($fileName, $fileType,$data)
  855. {
  856. //文件名称校验
  857. if (!$fileName) {
  858. trigger_error('文件名不能为空', E_USER_ERROR);
  859. }
  860. //Excel文件类型校验
  861. $type = ['Excel2007', 'Xlsx', 'Excel5', 'xls'];
  862. if (!in_array($fileType, $type)) {
  863. trigger_error('未知文件类型', E_USER_ERROR);
  864. }
  865. $ext = '';
  866. if ($fileType == 'Excel2007' || $fileType == 'Xlsx') {
  867. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  868. header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx"');
  869. header('Cache-Control: max-age=0');
  870. $ext = 'Xlsx';
  871. } else { //Excel5
  872. header('Content-Type: application/vnd.ms-excel');
  873. header('Content-Disposition: attachment;filename="' . $fileName . '.xls"');
  874. header('Cache-Control: max-age=0');
  875. $ext = 'Xls';
  876. }
  877. $spreadsheet = new Spreadsheet();
  878. $worksheet = $spreadsheet->getActiveSheet();
  879. $worksheet->getColumnDimension('A')->setWidth(15);
  880. $worksheet->getColumnDimension('B')->setWidth(15);
  881. $worksheet->getColumnDimension('C')->setWidth(15);
  882. $worksheet->getColumnDimension('D')->setWidth(15);
  883. $worksheet->getRowDimension('1')->setRowHeight(25);
  884. //设置工作表标题名称
  885. $worksheet->setTitle('学员信息');
  886. $worksheet->setCellValue('A1',"序号");
  887. $worksheet->setCellValue('B1',"学号");
  888. $worksheet->setCellValue('C1',"姓名");
  889. $worksheet->setCellValue('D1',"区队");
  890. foreach ($data as $ky => $value)
  891. {
  892. $qudui = Db::name('department')->where('id',$value['depart_id'])->value('name');
  893. $lie = $ky+2;
  894. $worksheet->setCellValue('A'.$lie,++$ky);
  895. $worksheet->setCellValue('B'.$lie,$value['username']);
  896. $worksheet->setCellValue('C'.$lie,$value['nickname']);
  897. $worksheet->setCellValue('D'.$lie,$qudui);
  898. }
  899. $titlestyleArray = [
  900. 'font' => [
  901. 'name' => '黑体',
  902. 'size' => 14
  903. ],
  904. ];
  905. $headerStyleArray = [
  906. 'font' => [
  907. 'name' => '方正小标宋简体',
  908. 'size' => 18
  909. ],
  910. ];
  911. $commonStyleArray = [
  912. 'alignment' => [
  913. 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
  914. 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
  915. 'wrapText' => true,
  916. ]
  917. ];
  918. $borderStyleArray = [
  919. 'borders' => [
  920. 'allBorders' => [
  921. 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
  922. ],
  923. ],
  924. 'font' => [
  925. 'name' => '黑体',
  926. ],
  927. ];
  928. $worksheet->getStyle('A1:D1')->applyFromArray($titlestyleArray);
  929. $worksheet->getStyle('A1:D1')->applyFromArray($commonStyleArray);
  930. // $worksheet->getStyle('A2:R2')->applyFromArray($commonStyleArray);
  931. // $worksheet->getStyle('A3:R3')->applyFromArray($commonStyleArray);
  932. // $worksheet->getStyle('A'.$footer_total.':R'.$footer_total)->applyFromArray($commonStyleArray);
  933. // $worksheet->getStyle('A1:C1')->applyFromArray($borderStyleArray);
  934. // $worksheet->mergeCells('A1:R1');
  935. $writer = IOFactory::createWriter($spreadsheet,$ext);
  936. $writer->save('php://output');
  937. die();
  938. }
  939. }