Admin.php 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  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. //更改姓名,同步更改考试表中的姓名
  304. Db::name('real_exam')->where('user_id', $row->id)->update(['user_nickname'=>$params['nickname']]);
  305. Db::commit();
  306. } catch (\Exception $e) {
  307. Db::rollback();
  308. $this->error($e->getMessage());
  309. }
  310. $this->success();
  311. }
  312. $this->error(__('Parameter %s can not be empty', ''));
  313. }
  314. $groupdata = DepartmentModel::getGroupdata(
  315. $this->childrenGroupIds,
  316. $this->auth->isSuperAdmin() ? null : $this->auth->getGroups()
  317. );
  318. $grouplist = $this->auth->getGroups($row['id']);
  319. $groupids = [];
  320. foreach ($grouplist as $k => $v) {
  321. $groupids[] = $v['id'];
  322. }
  323. $this->view->assign("groupids", $groupids);
  324. $this->view->assign('row', $row);
  325. $this->view->assign('department_ids', $this->dadminModel->getDepartmentIds($ids));
  326. $this->view->assign('groupdata', $groupdata);
  327. return $this->view->fetch();
  328. }
  329. /**
  330. * 删除
  331. */
  332. public function del($ids = "")
  333. {
  334. if (!$this->request->isPost()) {
  335. $this->error(__("Invalid parameters"));
  336. }
  337. $this->childrenAdminIds = $this->auth->getChildrenAdminIds($this->auth->isSuperAdmin());
  338. $this->model = new AdminModel();
  339. $ids = $ids ? $ids : $this->request->post("ids");
  340. if ($ids) {
  341. $ids = array_intersect($this->childrenAdminIds, array_filter(explode(',', $ids)));
  342. // 避免越权删除管理员
  343. $childrenGroupIds = $this->childrenGroupIds;
  344. $adminList = $this->model->where('id', 'in', $ids)->where('id', 'in', function ($query) use ($childrenGroupIds) {
  345. $query->name('auth_group_access')->where('group_id', 'in', $childrenGroupIds)->field('uid');
  346. })->select();
  347. if ($adminList) {
  348. $deleteIds = [];
  349. foreach ($adminList as $k => $v) {
  350. $deleteIds[] = $v->id;
  351. }
  352. $deleteIds = array_values(array_diff($deleteIds, [$this->auth->id]));
  353. if ($deleteIds) {
  354. Db::startTrans();
  355. try {
  356. $this->model->destroy($deleteIds);
  357. model('AuthGroupAccess')->where('uid', 'in', $deleteIds)->delete();
  358. //删除部门员工信息
  359. $this->dadminModel->where('admin_id', 'in', $deleteIds)->delete();;
  360. Db::commit();
  361. } catch (\Exception $e) {
  362. Db::rollback();
  363. $this->error($e->getMessage());
  364. }
  365. $this->success();
  366. }
  367. $this->error(__('No rows were deleted'));
  368. }
  369. }
  370. $this->error(__('You have no permission'));
  371. }
  372. /**
  373. * 批量更新
  374. */
  375. public function multi($ids = "")
  376. {
  377. $this->model = new AdminModel();
  378. return parent::multi($ids);
  379. }
  380. /**
  381. * 设置部门负责人
  382. */
  383. public function principal($ids = "")
  384. {
  385. $this->model = new AdminModel();
  386. $departmentModel = new DepartmentModel();
  387. $row = $this->model->get($ids);
  388. if ($this->request->isPost()) {
  389. //判断是不是超级管理员编辑
  390. if (!DepartmentAdminModel::isSuperAdmin($this->auth->id) && DepartmentAdminModel::isSuperAdmin($row->id)) {
  391. $this->error("您无权操作超级管理员");
  392. }
  393. $department_id = $this->request->post("department_id/a");
  394. if ($department_id && $department_id[0]) {
  395. Db::startTrans();
  396. try {
  397. $d_list = $departmentModel->where('id', 'in', $department_id)->select();
  398. if (!$d_list) {
  399. exception(__("Department can't null"));
  400. }
  401. //先移除他所有负责的部门
  402. $this->dadminModel->where('admin_id', $row->id)->update(['is_principal' => 0]);
  403. //判断选择的部门是否存在,不存在就先把他加入
  404. $p_departmentids = array_column($d_list, 'id');
  405. $exist_departmentids = $this->dadminModel->where('admin_id', $row->id)->column('department_id');
  406. $dadmin = array();
  407. //添加部门信息
  408. foreach ($d_list as $d_row) {
  409. if (!in_array($d_row->id, $exist_departmentids)) {
  410. $dadmin[] = ['department_id' => $d_row->id, 'organise_id' => $d_row->organise_id ? $d_row->organise_id : $d_row->id, 'admin_id' => $row->id];
  411. }
  412. }
  413. if (count($dadmin) > 0) {
  414. $this->dadminModel->saveAll($dadmin);
  415. }
  416. //更改为负责人
  417. $this->dadminModel->where('admin_id', $row->id)->where('department_id', 'in', $p_departmentids)->update(['is_principal' => 1]);
  418. Db::commit();
  419. } catch (\Exception $e) {
  420. Db::rollback();
  421. $this->error($e->getMessage());
  422. }
  423. } else {
  424. //移除他所有负责的部门
  425. $this->dadminModel->where('admin_id', $row->id)->update(['is_principal' => 0]);
  426. }
  427. $this->success();
  428. }
  429. $this->view->assign('row', $row);
  430. $this->view->assign('department_ids', $this->dadminModel::getPrincipalIds($ids));
  431. return $this->view->fetch();
  432. }
  433. /**
  434. * 获取员工的部门IDs
  435. */
  436. public function getDepartmentIds($id = ""){
  437. $departmentIds=DepartmentAdminModel::getDepartmentIds($id);
  438. //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
  439. $this->success("",'',['departmentIds' => $departmentIds]);
  440. }
  441. /**
  442. * 下拉选择
  443. * @Internal
  444. */
  445. public function selectpage()
  446. {
  447. $type=$this->request->request('type');//all代表选择所有
  448. $custom = ['status' => 'normal'];
  449. if ($type != "all") {
  450. $childrenAdminIds = \app\admin\model\department\Admin::getChildrenAdminIds($this->auth->id, true);
  451. $custom['id'] = ['in', $childrenAdminIds];
  452. }
  453. $this->selectpageFields = ['id', 'concat(nickname,"(",id,")") as nickname'];
  454. $this->request->request(['custom' => $custom]);
  455. //搜索字段
  456. $searchfield = (array)$this->request->request("searchField/a");
  457. $searchfield[]='id';
  458. $this->request->request(['searchField'=>$searchfield]);
  459. $this->model = model('admin');
  460. //设置过滤方法
  461. $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);
  462. //搜索关键词,客户端输入以空格分开,这里接收为数组
  463. $word = (array)$this->request->request("q_word/a");
  464. //当前页
  465. $page = $this->request->request("pageNumber");
  466. //分页大小
  467. $pagesize = $this->request->request("pageSize");
  468. //搜索条件
  469. $andor = $this->request->request("andOr", "and", "strtoupper");
  470. //排序方式
  471. $orderby = (array)$this->request->request("orderBy/a");
  472. //显示的字段
  473. $field = $this->request->request("showField");
  474. //主键
  475. $primarykey = $this->request->request("keyField");
  476. //主键值
  477. $primaryvalue = $this->request->request("keyValue");
  478. //搜索字段
  479. $searchfield = (array)$this->request->request("searchField/a");
  480. //自定义搜索条件
  481. $custom = (array)$this->request->request("custom/a");
  482. //是否返回树形结构
  483. $istree = $this->request->request("isTree", 0);
  484. $ishtml = $this->request->request("isHtml", 0);
  485. if ($istree) {
  486. $word = [];
  487. $pagesize = 999999;
  488. }
  489. $order = [];
  490. foreach ($orderby as $k => $v) {
  491. $order[$v[0]] = $v[1];
  492. }
  493. $field = $field ? $field : 'name';
  494. //如果有primaryvalue,说明当前是初始化传值
  495. if ($primaryvalue !== null) {
  496. $where = [$primarykey => ['in', $primaryvalue]];
  497. $pagesize = 999999;
  498. } else {
  499. $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
  500. $logic = $andor == 'AND' ? '&' : '|';
  501. $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
  502. $searchfield = str_replace(',', $logic, $searchfield);
  503. $word = array_filter(array_unique($word));
  504. if (count($word) == 1) {
  505. $query->where($searchfield, "like", "%" . reset($word) . "%");
  506. } else {
  507. $query->where(function ($query) use ($word, $searchfield) {
  508. foreach ($word as $index => $item) {
  509. $query->whereOr(function ($query) use ($item, $searchfield) {
  510. $query->where($searchfield, "like", "%{$item}%");
  511. });
  512. }
  513. });
  514. }
  515. if ($custom && is_array($custom)) {
  516. foreach ($custom as $k => $v) {
  517. if (is_array($v) && 2 == count($v)) {
  518. $query->where($k, trim($v[0]), $v[1]);
  519. } else {
  520. $query->where($k, '=', $v);
  521. }
  522. }
  523. }
  524. };
  525. }
  526. $adminIds = $this->getDataLimitAdminIds();
  527. if (is_array($adminIds)) {
  528. $this->model->where($this->dataLimitField, 'in', $adminIds);
  529. }
  530. $list = [];
  531. $total = $this->model->where($where)->count();
  532. if ($total > 0) {
  533. if (is_array($adminIds)) {
  534. $this->model->where($this->dataLimitField, 'in', $adminIds);
  535. }
  536. $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);
  537. //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
  538. if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
  539. $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
  540. //修复自定义data-primary-key为字符串内容时,给排序字段添加上引号
  541. $primaryvalue = array_map(function ($value) {
  542. return '\'' . $value . '\'';
  543. }, $primaryvalue);
  544. $primaryvalue = implode(',', $primaryvalue);
  545. $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
  546. } else {
  547. $this->model->order($order);
  548. }
  549. $datalist = $this->model->where($where)
  550. ->field($this->selectpageFields)
  551. ->page($page, $pagesize)
  552. ->select();
  553. foreach ($datalist as $index => $item) {
  554. unset($item['password'], $item['salt']);
  555. if ($this->selectpageFields == '*') {
  556. $result = [
  557. $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
  558. $field => isset($item[$field]) ? $item[$field] : '',
  559. ];
  560. } else {
  561. $result = (($item instanceof Model ? $item->toArray() : (array)$item));
  562. }
  563. $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
  564. $list[] = $result;
  565. }
  566. if ($istree && !$primaryvalue) {
  567. $tree = Tree::instance();
  568. $tree->init(collection($list)->toArray(), 'pid');
  569. $list = $tree->getTreeList($tree->getTreeArray(0), $field);
  570. if (!$ishtml) {
  571. foreach ($list as &$item) {
  572. $item = str_replace('&nbsp;', ' ', $item);
  573. }
  574. unset($item);
  575. }
  576. }
  577. }
  578. //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
  579. return json(['list' => $list, 'total' => $total]);
  580. }
  581. public function departadmintotal()
  582. {
  583. //设置过滤方法
  584. $this->request->filter(['strip_tags', 'trim']);
  585. if (false === $this->request->isAjax()) {
  586. return $this->view->fetch();
  587. }
  588. //如果发送的来源是 Selectpage,则转发到 Selectpage
  589. if ($this->request->request('keyField')) {
  590. return $this->selectpage();
  591. }
  592. [$where, $sort, $order, $offset, $limit] = $this->buildparams();
  593. $departmentModel = new DepartmentModel();
  594. $list = $departmentModel
  595. ->where($where)->where(['level'=>5])
  596. ->order($sort, $order)
  597. ->paginate($limit);
  598. foreach ($list as $k => $v){
  599. $v->department_name = '';
  600. if(!empty($v->parent_id)){
  601. $row = $departmentModel->where(['id'=>$v->parent_id])->find();
  602. if(!empty($row->parent_id)){
  603. $row2 = $departmentModel->where(['id'=>$row->parent_id])->find();
  604. if(!empty($row2->parent_id)){
  605. $row3 = $departmentModel->where(['id'=>$row2->parent_id])->find();
  606. if(!empty($row3->parent_id)) {
  607. $row4 = $departmentModel->where(['id' => $row3->parent_id])->find();
  608. $v->department_name = $row4['name'].">>".$row3['name'].">>".$row2['name'].">>".$row['name'].">>".$v['name'];
  609. }
  610. }
  611. }
  612. }
  613. $v->department_admin_count = Db::name('admin')->where(['depart_id'=>$v['id']])->count();
  614. $v->alluser = Db::name('admin')->where(['depart_id'=>$v['id']])->select();
  615. $v->user_ids = Db::name('admin')->where(['depart_id'=>$v['id']])->column('id');
  616. }
  617. unset($v);
  618. $result = ['total' => $list->total(), 'rows' => $list->items()];
  619. return json($result);
  620. }
  621. //导入
  622. public function import(){
  623. error_reporting(E_ALL);
  624. ini_set("memory_limit","8000M");
  625. $file = $this->request->request('file');
  626. if (!$file) {
  627. $this->error(__('Parameter %s can not be empty', 'file'));
  628. }
  629. $filePath = ROOT_PATH . DS . 'public' . DS . $file;
  630. if (!is_file($filePath)) {
  631. $this->error(__('No results were found'));
  632. }
  633. //实例化reader
  634. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  635. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  636. $this->error(__('Unknown data format'));
  637. }
  638. if ($ext === 'csv') {
  639. $file = fopen($filePath, 'r');
  640. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  641. $fp = fopen($filePath, "w");
  642. $n = 0;
  643. while ($line = fgets($file)) {
  644. $line = rtrim($line, "\n\r\0");
  645. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  646. if ($encoding != 'utf-8') {
  647. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  648. }
  649. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  650. fwrite($fp, $line . "\n");
  651. } else {
  652. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  653. }
  654. $n++;
  655. }
  656. fclose($file) || fclose($fp);
  657. $reader = new Csv();
  658. } elseif ($ext === 'xls') {
  659. $reader = new Xls();
  660. } else {
  661. $reader = new Xlsx();
  662. }
  663. //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
  664. $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
  665. $this->model = new \app\admin\model\department\AuthAdmin();
  666. $table = $this->model->getQuery()->getTable();
  667. $fieldArr['学员账号'] = 'username';
  668. $fieldArr['学员姓名'] = 'nickname';
  669. $fieldArr['层次'] = 'cengci';
  670. $fieldArr['专业'] = 'zhuanye';
  671. $fieldArr['年级'] = 'nianji';
  672. $fieldArr['队'] = 'dui';
  673. $fieldArr['区队'] = 'depart_id';
  674. //加载文件
  675. $insert = [];
  676. try {
  677. if (!$PHPExcel = $reader->load($filePath)) {
  678. $this->error(__('Unknown data format'));
  679. }
  680. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  681. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  682. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  683. $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  684. $fields = [];
  685. for ($currentRow = 2; $currentRow <= 2; $currentRow++) {
  686. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  687. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  688. $fields[] = $val;
  689. }
  690. }
  691. for ($currentRow = 3; $currentRow <= $allRow; $currentRow++) {
  692. $values = [];
  693. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  694. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  695. $values[] = is_null($val) ? '' : $val;
  696. }
  697. $row = [];
  698. $temp = array_combine($fields, $values);
  699. foreach ($temp as $k => $v) {
  700. if (isset($fieldArr[$k]) && $k !== '') {
  701. $row[$fieldArr[$k]] = trim($v);
  702. }
  703. }
  704. if ($row) {
  705. $insert[] = $row;
  706. }
  707. }
  708. } catch (Exception $exception) {
  709. $this->error($exception->getMessage());
  710. }
  711. if (!$insert) {
  712. $this->error(__('No rows were updated'));
  713. }
  714. $idcard_str = '';
  715. $insert_data = [];
  716. try {
  717. foreach ($insert as $key => $v)
  718. {
  719. if(!empty($v['username'])){
  720. if(empty($v['cengci'])){
  721. $idcard_str.= $v['nickname'].":层次不能为空<br/>";
  722. continue;
  723. }
  724. if(empty($v['zhuanye'])){
  725. $idcard_str.= $v['nickname'].":专业不能为空<br/>";
  726. continue;
  727. }
  728. if(empty($v['nianji'])){
  729. $idcard_str.= $v['nickname'].":年级不能为空<br/>";
  730. continue;
  731. }
  732. if(empty($v['dui'])){
  733. $idcard_str.= $v['nickname'].":队不能为空<br/>";
  734. continue;
  735. }
  736. if(empty($v['depart_id'])){
  737. $idcard_str.= $v['nickname'].":区队不能为空<br/>";
  738. continue;
  739. }
  740. //层次
  741. $cengci = Db::name('department')->where('name',$v['cengci'])->where('parent_id',0)->value('id');
  742. if(empty($cengci)){
  743. $idcard_str.= $v['nickname'].":层次有误,请核实是否存在<br/>";
  744. continue;
  745. }else{
  746. //专业
  747. $zhuanye = Db::name('department')->where('name',$v['zhuanye'])->where('parent_id',$cengci)->value('id');
  748. if(empty($zhuanye)){
  749. $idcard_str.= $v['nickname'].":专业有误,请核实是否存在或是否为层次下级<br/>";
  750. continue;
  751. }else{
  752. //年级
  753. $nianji = Db::name('department')->where('name',$v['nianji'])->where('parent_id',$zhuanye)->value('id');
  754. if(empty($nianji)){
  755. $idcard_str.= $v['nickname'].":年级有误,请核实是否存在或是否为专业下级<br/>";
  756. continue;
  757. }else{
  758. //队
  759. $dui = Db::name('department')->where('name',$v['dui'])->where('parent_id',$nianji)->value('id');
  760. if(empty($dui)){
  761. $idcard_str.= $v['nickname'].":队有误,请核实是否存在或是否为年级下级<br/>";
  762. continue;
  763. }else{
  764. //区队
  765. $depart_id = Db::name('department')->where('name',$v['depart_id'])->where('parent_id',$dui)->value('id');
  766. if(empty($depart_id)){
  767. $idcard_str.= $v['nickname'].":区队有误,请核实是否存在或是否为队下级<br/>";
  768. continue;
  769. }
  770. }
  771. }
  772. }
  773. }
  774. $admin_info = Db::name('admin')->where('username',$v['username'])->find();
  775. if(empty($admin_info)){
  776. $salt = Random::alnum();
  777. $insert = [
  778. 'username'=>$v['username'],
  779. 'nickname'=>$v['nickname'],
  780. 'salt'=>$salt,
  781. 'password'=>$this->auth->getEncryptPassword('123456', $salt),
  782. 'avatar'=>'/assets/img/avatar.png',
  783. 'loginfailure'=>0,
  784. 'email'=>$v['username'].'@163.com',
  785. 'status'=>'normal',
  786. 'createtime'=>time(),
  787. 'updatetime'=>time(),
  788. 'depart_id'=>$depart_id??0,
  789. ];
  790. $adminId = Db::name('admin')->insertGetId($insert);
  791. $add = [
  792. 'department_id'=>$depart_id??0,
  793. 'admin_id'=>$adminId,
  794. 'create_time'=>time(),
  795. 'update_time'=>time(),
  796. ];
  797. $departmentId = Db::name('department_admin')->insertGetId($add);
  798. $group_info = Db::name('auth_group_access')->where('uid',$adminId)->find();
  799. if(empty($group_info)){
  800. $arr = [
  801. 'uid'=>$adminId,
  802. 'group_id'=>8
  803. ];
  804. Db::name('auth_group_access')->insertGetId($arr);
  805. }
  806. }else{
  807. //已存在更新
  808. Db::name('admin')->where('id',$admin_info['id'])->update(['depart_id'=>$depart_id]);
  809. Db::name('department_admin')->where('admin_id',$admin_info['id'])->update(['department_id'=>$depart_id]);
  810. }
  811. }
  812. }
  813. } catch (PDOException $exception) {
  814. $msg = $exception->getMessage();
  815. if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
  816. $msg = "导入失败,包含【{$matches[1]}】的记录已存在";
  817. };
  818. $this->error($msg);
  819. } catch (Exception $e) {
  820. $this->error($e->getMessage());
  821. }
  822. if(!empty($idcard_str) ){
  823. $msg = '导入成功,';
  824. if (!empty($idcard_str)) {
  825. $msg .= '以下数据不合理:<br />' . $idcard_str;
  826. }
  827. $this->success($msg,'',[],15);
  828. }else{
  829. $this->success('导入成功');
  830. }
  831. }
  832. //导出
  833. public function export(){
  834. $this->model = new \app\admin\model\department\AuthAdmin();
  835. $department_id = $this->request->request("department_id");
  836. $filter = $this->request->get("filter", '');
  837. $filter = (array)json_decode($filter, true);
  838. $filter_w = [];
  839. if (isset($filter['department_id'])) {
  840. $department_id = $filter['department_id'];
  841. unset($filter['department_id']);
  842. $this->request->get(['filter' => json_encode($filter)]);
  843. }
  844. if ($department_id) {
  845. $filter_w['depart_id'] = ['in', $department_id];
  846. }
  847. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  848. $list = $this->model->where($where)->where(['depart_id'=>['>',0]])->where($filter_w)->order($sort, $order)->select();
  849. $xlsName = '学员信息';
  850. $this->exportExcel($xlsName,'Excel2007', $list);
  851. }
  852. /**
  853. * 输出到浏览器(需要设置header头)
  854. * @param string $fileName 文件名
  855. * @param string $fileType 文件类型
  856. */
  857. function exportExcel($fileName, $fileType,$data)
  858. {
  859. //文件名称校验
  860. if (!$fileName) {
  861. trigger_error('文件名不能为空', E_USER_ERROR);
  862. }
  863. //Excel文件类型校验
  864. $type = ['Excel2007', 'Xlsx', 'Excel5', 'xls'];
  865. if (!in_array($fileType, $type)) {
  866. trigger_error('未知文件类型', E_USER_ERROR);
  867. }
  868. $ext = '';
  869. if ($fileType == 'Excel2007' || $fileType == 'Xlsx') {
  870. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  871. header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx"');
  872. header('Cache-Control: max-age=0');
  873. $ext = 'Xlsx';
  874. } else { //Excel5
  875. header('Content-Type: application/vnd.ms-excel');
  876. header('Content-Disposition: attachment;filename="' . $fileName . '.xls"');
  877. header('Cache-Control: max-age=0');
  878. $ext = 'Xls';
  879. }
  880. $spreadsheet = new Spreadsheet();
  881. $worksheet = $spreadsheet->getActiveSheet();
  882. $worksheet->getColumnDimension('A')->setWidth(15);
  883. $worksheet->getColumnDimension('B')->setWidth(15);
  884. $worksheet->getColumnDimension('C')->setWidth(15);
  885. $worksheet->getColumnDimension('D')->setWidth(15);
  886. $worksheet->getRowDimension('1')->setRowHeight(25);
  887. //设置工作表标题名称
  888. $worksheet->setTitle('学员信息');
  889. $worksheet->setCellValue('A1',"序号");
  890. $worksheet->setCellValue('B1',"学员账号");
  891. $worksheet->setCellValue('C1',"学员姓名");
  892. $worksheet->setCellValue('D1',"区队");
  893. foreach ($data as $ky => $value)
  894. {
  895. $qudui = Db::name('department')->where('id',$value['depart_id'])->value('name');
  896. $lie = $ky+2;
  897. $worksheet->setCellValue('A'.$lie,++$ky);
  898. $worksheet->setCellValue('B'.$lie,$value['username']);
  899. $worksheet->setCellValue('C'.$lie,$value['nickname']);
  900. $worksheet->setCellValue('D'.$lie,$qudui);
  901. }
  902. $titlestyleArray = [
  903. 'font' => [
  904. 'name' => '黑体',
  905. 'size' => 14
  906. ],
  907. ];
  908. $headerStyleArray = [
  909. 'font' => [
  910. 'name' => '方正小标宋简体',
  911. 'size' => 18
  912. ],
  913. ];
  914. $commonStyleArray = [
  915. 'alignment' => [
  916. 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
  917. 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
  918. 'wrapText' => true,
  919. ]
  920. ];
  921. $borderStyleArray = [
  922. 'borders' => [
  923. 'allBorders' => [
  924. 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
  925. ],
  926. ],
  927. 'font' => [
  928. 'name' => '黑体',
  929. ],
  930. ];
  931. $worksheet->getStyle('A1:D1')->applyFromArray($titlestyleArray);
  932. $worksheet->getStyle('A1:D1')->applyFromArray($commonStyleArray);
  933. // $worksheet->getStyle('A2:R2')->applyFromArray($commonStyleArray);
  934. // $worksheet->getStyle('A3:R3')->applyFromArray($commonStyleArray);
  935. // $worksheet->getStyle('A'.$footer_total.':R'.$footer_total)->applyFromArray($commonStyleArray);
  936. // $worksheet->getStyle('A1:C1')->applyFromArray($borderStyleArray);
  937. // $worksheet->mergeCells('A1:R1');
  938. $writer = IOFactory::createWriter($spreadsheet,$ext);
  939. $writer->save('php://output');
  940. die();
  941. }
  942. }