User.php 19 KB

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