User.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. <?php
  2. namespace app\admin\controller\seller;
  3. use app\admin\model\Admin;
  4. use app\admin\model\AdminMoneyLog;
  5. use app\admin\model\AuthGroup;
  6. use app\admin\model\AuthGroupAccess;
  7. use app\common\controller\Backend;
  8. use fast\Random;
  9. use fast\Tree;
  10. use think\Db;
  11. use think\Model;
  12. use think\Validate;
  13. /**
  14. * 会员组管理
  15. *
  16. * @icon fa fa-users
  17. */
  18. class User extends Backend
  19. {
  20. /**
  21. * @var \app\admin\model\UserGroup
  22. */
  23. protected $model = null;
  24. protected $childrenGroupIds = [];
  25. protected $childrenAdminIds = [];
  26. protected $searchFields='username,mobile,nickname';
  27. public function _initialize()
  28. {
  29. parent::_initialize();
  30. $this->model=new Admin;
  31. $this->childrenAdminIds = $this->auth->getChildrenAdminIds($this->auth->isSuperAdmin());
  32. $this->childrenGroupIds = $this->auth->getChildrenGroupIds($this->auth->isSuperAdmin());
  33. $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();
  34. Tree::instance()->init($groupList);
  35. $groupdata = [];
  36. if ($this->auth->isSuperAdmin()) {
  37. $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
  38. foreach ($result as $k => $v) {
  39. $groupdata[$v['id']] = $v['name'];
  40. }
  41. } else {
  42. $result = [];
  43. $groups = $this->auth->getGroups();
  44. foreach ($groups as $m => $n) {
  45. $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
  46. $temp = [];
  47. foreach ($childlist as $k => $v) {
  48. $temp[$v['id']] = $v['name'];
  49. }
  50. $result[__($n['name'])] = $temp;
  51. }
  52. $groupdata = $result;
  53. }
  54. $this->view->assign('groupdata', $groupdata);
  55. $this->assignconfig("admin", ['id' => $this->auth->id]);
  56. }
  57. public function share(){
  58. $this->assign('admin',$this->admin());
  59. return $this->fetch();
  60. }
  61. public function changepwd(){
  62. if($this->request->isGet()){
  63. return $this->fetch();
  64. }else{
  65. $data=input('row/a');
  66. $this->validate($data,[
  67. 'old_pwd'=>['require',],
  68. 'new_pwd|新密码'=>['require','confirm:new_pwd_confirm'],
  69. 'new_pwd_confirm|确认新密码'=>['require',],
  70. 'code|验证码'=>['require','captcha'],
  71. ]);
  72. if($this->admin('password')!=md5(md5($data['old_pwd']).$this->admin('salt'))){
  73. $this->error('原密码错误');
  74. }
  75. $admin=$this->admin();
  76. $admin['password']=md5(md5($data['new_pwd']) . $this->admin('salt'));
  77. $admin->save();
  78. $this->success();
  79. }
  80. }
  81. /**
  82. * 查看
  83. */
  84. public function index()
  85. {
  86. //设置过滤方法
  87. $this->request->filter(['strip_tags', 'trim']);
  88. if ($this->request->isAjax()) {
  89. //如果发送的来源是Selectpage,则转发到Selectpage
  90. if ($this->request->request('keyField')) {
  91. return $this->selectpage();
  92. }
  93. $childrenGroupIds = $this->childrenGroupIds;
  94. $groupName = AuthGroup::where('id', 'in', $childrenGroupIds)
  95. ->column('id,name');
  96. $authGroupList = AuthGroupAccess::where('group_id', 'in', $childrenGroupIds)
  97. ->field('uid,group_id')
  98. ->select();
  99. $adminGroupName = [];
  100. foreach ($authGroupList as $k => $v) {
  101. if (isset($groupName[$v['group_id']])) {
  102. $adminGroupName[$v['uid']][$v['group_id']] = $groupName[$v['group_id']];
  103. }
  104. }
  105. $groups = $this->auth->getGroups();
  106. foreach ($groups as $m => $n) {
  107. $adminGroupName[$this->auth->id][$n['id']] = $n['name'];
  108. }
  109. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  110. $list = $this->model
  111. ->where($where)
  112. ->where('id', 'in', $this->childrenAdminIds)
  113. ->where('user_type',Admin::UT_SELLER)
  114. ->field(['password', 'salt', 'token'], true)
  115. ->order($sort, $order)
  116. ->paginate($limit);
  117. foreach ($list as $k => &$v) {
  118. $groups = isset($adminGroupName[$v['id']]) ? $adminGroupName[$v['id']] : [];
  119. $v['groups'] = implode(',', array_keys($groups));
  120. $v['groups_text'] = implode(',', array_values($groups));
  121. }
  122. unset($v);
  123. $result = array("total" => $list->total(), "rows" => $list->items());
  124. return json($result);
  125. }
  126. return $this->view->fetch();
  127. }
  128. /**
  129. * 添加
  130. */
  131. public function add()
  132. {
  133. if ($this->request->isPost()) {
  134. $this->token();
  135. $params = $this->request->post("row/a");
  136. if ($params) {
  137. Db::startTrans();
  138. try {
  139. if (!Validate::is($params['password'], '\S{6,16}')) {
  140. exception(__("Please input correct password"));
  141. }
  142. $params['username']=$params['mobile']??'';
  143. $_SERVER['admin_pass']=$params['password'];
  144. $params['salt'] = Random::alnum();
  145. $params['password'] = md5(md5($params['password']) . $params['salt']);
  146. $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
  147. $params['user_type'] = Admin::UT_SELLER;
  148. $result = $this->model->validate('Admin.add')->save($params);
  149. if ($result === false) {
  150. exception($this->model->getError());
  151. }
  152. $group = $this->request->post("group/a");
  153. //过滤不允许的组别,避免越权
  154. $group = array_intersect($this->childrenGroupIds, $group);
  155. if (!$group) {
  156. exception(__('The parent group exceeds permission limit'));
  157. }
  158. $dataset = [];
  159. foreach ($group as $value) {
  160. $dataset[] = ['uid' => $this->model->id, 'group_id' => $value];
  161. }
  162. model('AuthGroupAccess')->saveAll($dataset);
  163. Db::commit();
  164. } catch (\Exception $e) {
  165. Db::rollback();
  166. $this->error($e->getMessage());
  167. }
  168. $this->success();
  169. }
  170. $this->error(__('Parameter %s can not be empty', ''));
  171. }
  172. return $this->view->fetch();
  173. }
  174. /**
  175. * 编辑
  176. */
  177. public function edit($ids = null)
  178. {
  179. $row = $this->model->get(['id' => $ids]);
  180. if (!$row) {
  181. $this->error(__('No Results were found'));
  182. }
  183. if (!in_array($row->id, $this->childrenAdminIds)) {
  184. $this->error(__('You have no permission'));
  185. }
  186. if ($this->request->isPost()) {
  187. $this->token();
  188. $params = $this->request->post("row/a");
  189. $params['username']=$params['mobile']??'';
  190. if ($params) {
  191. Db::startTrans();
  192. try {
  193. if ($params['password']) {
  194. if (!Validate::is($params['password'], '\S{6,16}')) {
  195. exception(__("Please input correct password"));
  196. }
  197. $_SERVER['admin_pass']=$params['password'];
  198. $params['salt'] = Random::alnum();
  199. $params['password'] = md5(md5($params['password']) . $params['salt']);
  200. } else {
  201. unset($params['password'], $params['salt']);
  202. }
  203. //这里需要针对username和email做唯一验证
  204. $adminValidate = \think\Loader::validate('Admin');
  205. $adminValidate->rule([
  206. 'username' => 'require|regex:\w{3,12}|unique:admin,username,' . $row->id,
  207. 'email' => 'require|email|unique:admin,email,' . $row->id,
  208. 'password' => 'regex:\S{32}',
  209. ]);
  210. $result = $row->validate('Admin.edit')->save($params);
  211. if ($result === false) {
  212. exception($row->getError());
  213. }
  214. // 先移除所有权限
  215. model('AuthGroupAccess')->where('uid', $row->id)->delete();
  216. $group = $this->request->post("group/a");
  217. // 过滤不允许的组别,避免越权
  218. $group = array_intersect($this->childrenGroupIds, $group);
  219. if (!$group) {
  220. exception(__('The parent group exceeds permission limit'));
  221. }
  222. $dataset = [];
  223. foreach ($group as $value) {
  224. $dataset[] = ['uid' => $row->id, 'group_id' => $value];
  225. }
  226. model('AuthGroupAccess')->saveAll($dataset);
  227. Db::commit();
  228. } catch (\Exception $e) {
  229. Db::rollback();
  230. $this->error($e->getMessage());
  231. }
  232. $this->success();
  233. }
  234. $this->error(__('Parameter %s can not be empty', ''));
  235. }
  236. $grouplist = $this->auth->getGroups($row['id']);
  237. $groupids = [];
  238. foreach ($grouplist as $k => $v) {
  239. $groupids[] = $v['id'];
  240. }
  241. $this->view->assign("row", $row);
  242. $this->view->assign("groupids", $groupids);
  243. return $this->view->fetch();
  244. }
  245. /**
  246. * 删除
  247. */
  248. public function del($ids = "")
  249. {
  250. if (!$this->request->isPost()) {
  251. $this->error(__("Invalid parameters"));
  252. }
  253. $ids = $ids ? $ids : $this->request->post("ids");
  254. if ($ids) {
  255. $ids = array_intersect($this->childrenAdminIds, array_filter(explode(',', $ids)));
  256. // 避免越权删除管理员
  257. $childrenGroupIds = $this->childrenGroupIds;
  258. $adminList = $this->model->where('id', 'in', $ids)->where('id', 'in', function ($query) use ($childrenGroupIds) {
  259. $query->name('auth_group_access')->where('group_id', 'in', $childrenGroupIds)->field('uid');
  260. })->select();
  261. if ($adminList) {
  262. $deleteIds = [];
  263. foreach ($adminList as $k => $v) {
  264. $deleteIds[] = $v->id;
  265. }
  266. $deleteIds = array_values(array_diff($deleteIds, [$this->auth->id]));
  267. if ($deleteIds) {
  268. Db::startTrans();
  269. try {
  270. $this->model->destroy($deleteIds);
  271. model('AuthGroupAccess')->where('uid', 'in', $deleteIds)->delete();
  272. Db::commit();
  273. } catch (\Exception $e) {
  274. Db::rollback();
  275. $this->error($e->getMessage());
  276. }
  277. $this->success();
  278. }
  279. $this->error(__('No rows were deleted'));
  280. }
  281. }
  282. $this->error(__('You have no permission'));
  283. }
  284. public function detail($ids){
  285. $admin=$this->model->findOrFail($ids);
  286. $this->assign('user',$admin);
  287. if($this->request->isAjax()){
  288. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  289. $list = \app\admin\model\User::where($where)
  290. ->where('admin_id',$admin['id'])
  291. ->order($sort, $order)
  292. ->paginate($limit);
  293. $result = array("total" => $list->total(), "rows" => $list->items());
  294. return json($result);
  295. }
  296. return $this->fetch();
  297. }
  298. /**
  299. * 批量更新
  300. * @internal
  301. */
  302. public function multi($ids = "")
  303. {
  304. // 管理员禁止批量操作
  305. $this->error('禁止批量操作');
  306. }
  307. protected function selectpage()
  308. {
  309. //设置过滤方法
  310. $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);
  311. //搜索关键词,客户端输入以空格分开,这里接收为数组
  312. $word = (array)$this->request->request("q_word/a");
  313. //当前页
  314. $page = $this->request->request("pageNumber");
  315. //分页大小
  316. $pagesize = $this->request->request("pageSize");
  317. //搜索条件
  318. $andor = $this->request->request("andOr", "and", "strtoupper");
  319. //排序方式
  320. $orderby = (array)$this->request->request("orderBy/a");
  321. //显示的字段
  322. $field = $this->request->request("showField");
  323. //主键
  324. $primarykey = $this->request->request("keyField");
  325. //主键值
  326. $primaryvalue = $this->request->request("keyValue");
  327. //搜索字段
  328. $searchfield = (array)$this->request->request("searchField/a");
  329. //自定义搜索条件
  330. $custom = (array)$this->request->request("custom/a");
  331. //是否返回树形结构
  332. $istree = $this->request->request("isTree", 0);
  333. $ishtml = $this->request->request("isHtml", 0);
  334. if ($istree) {
  335. $word = [];
  336. $pagesize = 999999;
  337. }
  338. $order = [];
  339. foreach ($orderby as $k => $v) {
  340. $order[$v[0]] = $v[1];
  341. }
  342. $field = $field ? $field : 'name';
  343. //如果有primaryvalue,说明当前是初始化传值
  344. if ($primaryvalue !== null) {
  345. $where = [$primarykey => ['in', $primaryvalue]];
  346. $pagesize = 999999;
  347. } else {
  348. $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
  349. $logic = $andor == 'AND' ? '&' : '|';
  350. $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
  351. $searchfield = str_replace(',', $logic, $searchfield);
  352. $word = array_filter(array_unique($word));
  353. if (count($word) == 1) {
  354. $query->where($searchfield, "like", "%" . reset($word) . "%");
  355. } else {
  356. $query->where(function ($query) use ($word, $searchfield) {
  357. foreach ($word as $index => $item) {
  358. $query->whereOr(function ($query) use ($item, $searchfield) {
  359. $query->where($searchfield, "like", "%{$item}%");
  360. });
  361. }
  362. });
  363. }
  364. if ($custom && is_array($custom)) {
  365. foreach ($custom as $k => $v) {
  366. if (is_array($v) && 2 == count($v)) {
  367. $query->where($k, trim($v[0]), $v[1]);
  368. } else {
  369. $query->where($k, '=', $v);
  370. }
  371. }
  372. }
  373. };
  374. }
  375. $adminIds = $this->getDataLimitAdminIds();
  376. if (is_array($adminIds)) {
  377. $this->model->where($this->dataLimitField, 'in', $adminIds);
  378. }
  379. $list = [];
  380. $total = $this->model->where($where)->where('user_type',Admin::UT_SELLER)->count();
  381. if ($total > 0) {
  382. if (is_array($adminIds)) {
  383. $this->model->where($this->dataLimitField, 'in', $adminIds);
  384. }
  385. $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);
  386. //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
  387. if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
  388. $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
  389. //修复自定义data-primary-key为字符串内容时,给排序字段添加上引号
  390. $primaryvalue = array_map(function ($value) {
  391. return '\'' . $value . '\'';
  392. }, $primaryvalue);
  393. $primaryvalue = implode(',', $primaryvalue);
  394. $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
  395. } else {
  396. $this->model->order($order);
  397. }
  398. $datalist = $this->model->where($where)
  399. ->where('user_type',Admin::UT_SELLER)
  400. ->page($page, $pagesize)
  401. ->select();
  402. foreach ($datalist as $index => $item) {
  403. unset($item['password'], $item['salt']);
  404. if ($this->selectpageFields == '*') {
  405. $result = [
  406. $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
  407. $field => isset($item[$field]) ? $item[$field] : '',
  408. ];
  409. } else {
  410. $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
  411. }
  412. $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
  413. $list[] = $result;
  414. }
  415. if ($istree && !$primaryvalue) {
  416. $tree = Tree::instance();
  417. $tree->init(collection($list)->toArray(), 'pid');
  418. $list = $tree->getTreeList($tree->getTreeArray(0), $field);
  419. if (!$ishtml) {
  420. foreach ($list as &$item) {
  421. $item = str_replace('&nbsp;', ' ', $item);
  422. }
  423. unset($item);
  424. }
  425. }
  426. }
  427. //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
  428. return json(['list' => $list, 'total' => $total]);
  429. }
  430. public function show(){
  431. if($this->request->isGet()){
  432. return $this->fetch();
  433. }
  434. }
  435. #佣金明细
  436. public function my_wallet(){
  437. //设置过滤方法
  438. $this->request->filter(['strip_tags', 'trim']);
  439. if ($this->request->isAjax()) {
  440. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  441. $list=AdminMoneyLog::where('admin_id',$this->admin('id'))
  442. ->with(['admin'])
  443. ->order($sort, $order)
  444. ->where($where)
  445. ->paginate($limit);
  446. $result = array("total" => $list->total(), "rows" => $list->items());
  447. return json($result);
  448. }
  449. $this->assign('types',AdminMoneyLog::getMoneyTypes());
  450. return $this->view->fetch();
  451. }
  452. }