Admin.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. <?php
  2. namespace app\admin\controller;
  3. use app\BaseController;
  4. use app\admin\model\Admin as AdminModel;
  5. use app\admin\model\RoleMenu;
  6. use app\admin\model\Menu;
  7. use think\exception\Exception;
  8. use think\facade\Db;
  9. use app\admin\validate\AdminValidate;
  10. use app\admin\model\User;
  11. use app\admin\model\KefuWork;
  12. use think\facade\Session;
  13. use app\admin\model\KefuTime;
  14. use thans\jwt\facade\JWTAuth;
  15. use app\admin\model\Department;
  16. use app\admin\model\Role;
  17. class Admin extends BaseController
  18. {
  19. protected $noNeedLogin = ['login'];
  20. /**
  21. * @api {get} /list 查询管理员列表
  22. */
  23. public function list()
  24. {
  25. try {
  26. $params = $this->request->param();
  27. $query = new AdminModel();
  28. if (!empty($params['username'])) {
  29. $query = $query->where('username', 'like', "%{$params['username']}%");
  30. }
  31. if (!empty($params['phone'])) {
  32. $query = $query->where('phone', 'like', "%{$params['phone']}%");
  33. }
  34. if (isset($params['is_kefu']) && $params['is_kefu'] != '') {
  35. $query = $query->where('is_kefu', $params['is_kefu']);
  36. }
  37. if (!empty($params['role_id'])) {
  38. $query = $query->where('role_id', $params['role_id']);
  39. }
  40. if (!empty($params['department_id'])) {
  41. $query = $query->where('department_id', $params['department_id']);
  42. }
  43. $page = isset($params['page']) ? intval($params['page']) : 1;
  44. $limit = isset($params['limit']) ? intval($params['limit']) : 15;
  45. $count = $query->count();
  46. $list = $query->with(['role', 'department'])
  47. ->order('id', 'desc')
  48. ->limit($limit)
  49. ->page($page)
  50. ->select();
  51. } catch (\Exception $e) {
  52. return $this->error('查询失败:'.$e->getMessage());
  53. }
  54. return $this->success(['count' => $count, 'list' => $list]);
  55. }
  56. /**
  57. * @api {post} /update 添加/修改管理员
  58. */
  59. public function update()
  60. {
  61. Db::startTrans();
  62. try {
  63. $params = (new AdminValidate())->post()->goCheck('add');
  64. $id = $this->request->param('id');
  65. // 只允许超级管理员配置
  66. if ($this->admin_id != 1) {
  67. return $this->error('只有超级管理员才能操作');
  68. }
  69. if (empty($id)) {
  70. // 新增校验
  71. if (empty($params['password'])) {
  72. return $this->error('密码不能为空');
  73. }
  74. if (empty($params['role_id'])) {
  75. return $this->error('角色ID不能为空');
  76. }
  77. if (empty($params['department_id'])) {
  78. return $this->error('部门ID不能为空');
  79. }
  80. } elseif ($id != 1) {
  81. if (empty($params['role_id'])) {
  82. return $this->error('角色ID不能为空');
  83. }
  84. if (empty($params['department_id'])) {
  85. return $this->error('部门ID不能为空');
  86. }
  87. }
  88. if (!empty($params['password'])) {
  89. $params['password'] = password_hash($params['password'], PASSWORD_DEFAULT);
  90. } else {
  91. unset($params['password']);
  92. }
  93. if (!empty($params['payment_password'])) {
  94. $params['payment_password'] = password_hash($params['payment_password'], PASSWORD_DEFAULT);
  95. } else {
  96. unset($params['payment_password']);
  97. }
  98. $usernameCount = AdminModel::where('username', $params['username'])
  99. ->where('id', '<>', $id ?? 0)
  100. ->count();
  101. if ($usernameCount > 0) {
  102. return $this->error('用户名已存在');
  103. }
  104. $role = $params['is_kefu'] == 1 ? 3 : 2;//获取角色类型:1超管;2普管;3客服
  105. if (!empty($id)) {
  106. if ($id == 1) {
  107. $role = 1;
  108. }
  109. unset($params['username']);
  110. AdminModel::where('id', $id)->update($params);
  111. User::where('uid', $id)->where('from', 0)->update(['role' => $role, 'realname' => $params['nickname'], 'phone' => $params['phone'], 'remark' => $params['remark']]);
  112. } else {
  113. $admin = AdminModel::create($params);
  114. //插入user
  115. $params['id'] = $admin->id;
  116. $params['role'] = $role;
  117. User::addCs($params);
  118. }
  119. Db::commit();
  120. } catch (\Exception $e) {
  121. Db::rollback();
  122. return $this->error($e->getMessage());
  123. }
  124. return $this->success([],'操作成功');
  125. }
  126. // 删除管理员
  127. public function delete()
  128. {
  129. try {
  130. $params = (new AdminValidate())->goCheck('del');
  131. // 只允许超级管理员配置
  132. if ($this->admin_id != 1) {
  133. return $this->error('只有超级管理员才能操作');
  134. }
  135. if ($params['id'] == 1) {
  136. return $this->error('超级管理员不能删除');
  137. }
  138. // TP 删除语法
  139. AdminModel::where('id', $params['id'])->delete();
  140. } catch (\Exception $e) {
  141. return $this->error('删除失败:'.$e->getMessage());
  142. }
  143. return $this->success([],'删除成功');
  144. }
  145. /**
  146. * @api {post} /setPassword 修改登录密码
  147. */
  148. public function setPassword()
  149. {
  150. Db::startTrans();
  151. try {
  152. $params = (new AdminValidate())->post()->goCheck('password');
  153. $user = AdminModel::find($this->admin_id);
  154. if (!$user) {
  155. throw new \Exception('用户不存在');
  156. }
  157. // 校验旧密码
  158. if (!password_verify($params['old_password'], $user->password)) {
  159. throw new \Exception('密码错误');
  160. }
  161. // 更新登录密码
  162. $user->password = password_hash($params['password'], PASSWORD_DEFAULT);
  163. $user->save();
  164. Db::commit();
  165. } catch (\Exception $e) {
  166. Db::rollback();
  167. return $this->error($e->getMessage());
  168. }
  169. }
  170. /**
  171. * @api {post} /login 管理员登录
  172. */
  173. public function login()
  174. {
  175. // 登录无需事务,移除多余的 Db::startTrans()
  176. try {
  177. $params = (new AdminValidate())->post()->goCheck('login');
  178. $admin = AdminModel::where('username', $params['username'])->find();
  179. if (!$admin) {
  180. throw new \Exception('账号不存在');
  181. }
  182. if (!password_verify($params['password'], $admin->password)) {
  183. throw new \Exception('密码错误');
  184. }
  185. // 获取角色权限(优化 TP 查询语法)
  186. if ($admin->role_id && $admin->id > 1) {
  187. $admin->role_menu = RoleMenu::alias('rm')
  188. ->join('menu m', 'rm.menu_id = m.id','left')
  189. ->where('rm.role_id', $admin->role_id)
  190. ->where('m.status', 1)
  191. ->field(['m.id', 'm.parent_id', 'm.type', 'm.name', 'm.perms', 'm.paths', 'm.component', 'm.params', 'm.is_cache', 'm.sort'])
  192. ->order('m.sort', 'asc')
  193. ->select()
  194. ->toArray();
  195. } else {
  196. $admin->role_menu = Menu::alias('m')
  197. ->where('m.status', 1)
  198. ->field(['m.id', 'm.parent_id', 'm.type', 'm.name', 'm.perms', 'm.paths', 'm.component', 'm.params', 'm.is_cache', 'm.sort'])
  199. ->order('m.sort', 'asc')
  200. ->select()
  201. ->toArray();
  202. }
  203. $admin->role_name = Role::where('id', $admin->role_id)->value('name');
  204. $admin->department_name = Department::where('id', $admin->department_id)->value('name');
  205. //标记需要签到
  206. AdminModel::where('id', $admin->id)->update(['is_sign' => 1]);
  207. //如果登录信息中含有client——id则自动进行绑定
  208. $userInfo = User::where('account', $admin->username)->where('role', '>', 0)->find();
  209. if(!$userInfo){
  210. throw new \Exception('用户不存在');
  211. }
  212. if(!empty($params['client_id'])){
  213. $cid = $this->request->header('cid','');
  214. doBindUid($userInfo['user_id'],$params['client_id'],$cid,$this->request->isMobile());
  215. }
  216. $update=[
  217. 'last_login_time' => time(),
  218. 'last_login_ip' => $this->request->ip(),
  219. 'login_count' => Db::raw('login_count+1'),
  220. 'is_online' => 1,
  221. 'chat_num' => 0,
  222. 'is_finished' => 0,
  223. ];
  224. User::where('user_id',$userInfo['user_id'])->update($update);
  225. $userInfo['qrUrl']=getMainHost().'/scan/u/'.encryptIds($userInfo['user_id']);
  226. unset($userInfo['password'],$userInfo['salt']);
  227. $userInfo['displayName']=$userInfo['realname'];
  228. $userInfo['id']=$userInfo['user_id'];
  229. $authToken=User::refreshToken($userInfo,$param['terminal'] ?? 'web', ['id' => $admin->id, 'role_id' => $admin->role_id]);
  230. $data=[
  231. 'sessionId'=>Session::getId(),
  232. 'token' => $authToken,
  233. 'userInfo'=>$userInfo,
  234. 'adminInfo' => $admin,
  235. ];
  236. //判断是否是客服
  237. if ($userInfo['role'] == 3) {
  238. //通知客服签到
  239. wsSendMsg($userInfo['id'],'sign',['is_sign'=>1]);
  240. //添加客服登录时间
  241. KefuTime::addData($admin->id, 4);
  242. //添加客服在线时间
  243. KefuTime::addData($admin->id, 2);
  244. //添加客服上线次数
  245. KefuWork::addNum($admin->id, 'online_num');
  246. }
  247. } catch (\Exception $e) {
  248. return $this->error($e->getMessage());
  249. }
  250. return $this->success($data, '登录成功');
  251. }
  252. //获取是否需要签到
  253. public function getSign() {
  254. $is_sign = AdminModel::where('id', $this->admin_id)->value('is_sign');
  255. return $this->success(['is_sign' => $is_sign]);
  256. }
  257. //退出登录
  258. public function logout(){
  259. try {
  260. $jwtData = JWTAuth::auth();
  261. } catch (\Exception $e) {
  262. return success(lang('退出成功'));
  263. }
  264. $userInfo = $jwtData['info']->getValue();
  265. //解密token中的用户信息
  266. $userInfo = str_encipher($userInfo,false, config('app.aes_token_key'));
  267. if (!$userInfo) {
  268. return success(lang('退出成功'));
  269. }
  270. //解析json
  271. $userInfo = (array)json_decode($userInfo, true);
  272. if($userInfo){
  273. //结束客服服务时间
  274. KefuTime::endData($this->admin_id, 4);
  275. //客服离线后自动结束所有客服会话
  276. User::KefuOffline($userInfo['user_id'], $this->admin_id);
  277. }
  278. JWTAuth::invalidate(JWTAuth::token()->get());
  279. return success(lang('退出成功'));
  280. }
  281. }