Admin.php 12 KB

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