AdminService.php 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /**
  3. * Author: luzheng.liu
  4. * Time: 2021/2/4 19:38
  5. */
  6. namespace app\common\service;
  7. use app\api\exception\ApiException;
  8. use app\api\model\AdminModel;
  9. use think\Exception;
  10. class AdminService {
  11. public function encodePasswd(string $passwd) {
  12. return md5($passwd . '-Bjx14Nb3Le9ghOmM');
  13. }
  14. public function addAdmin($input) {
  15. $model = new AdminModel();
  16. if (empty($input['password'])) {
  17. throw new ApiException('密码不为空');
  18. }
  19. $info = $model::where(['account' => $input['account']])->find();
  20. if ($info !== null){
  21. throw new ApiException('管理员账号不能重复!');
  22. }
  23. $info = $model::where(['admin_code' => $input['adminCode']])->find();
  24. if ($info !== null){
  25. throw new ApiException('管理员工号不能重复!');
  26. }
  27. try {
  28. $model->startTrans();
  29. $id = $model->insertGetId([
  30. 'name' => $input['name'],
  31. 'account' => $input['account'],
  32. 'role_id' => $input['roleId'],
  33. 'password' => $this->encodePasswd($input['password']),
  34. 'mobile' => $input['mobile'],
  35. 'admin_code' => $input['adminCode'],
  36. 'status' => $input['status'] ?? 1,
  37. 'mac_address' => $input['macAddress'] ?? ''
  38. ]);
  39. if(!empty($input['storeIds'])) {
  40. $model->saveStoreRole($input['storeIds'], (int)$id);
  41. }
  42. $model->saveGroupRole($input['groupIds'], (int)$id);
  43. $model->commit();
  44. } catch (Exception $e) {
  45. $model->rollback();
  46. throw new ApiException($e->getMessage());
  47. }
  48. return $id;
  49. }
  50. public function editAdmin($input) {
  51. $model = new AdminModel();
  52. $id = (int)$input['id'];
  53. $rs = $model::where([['id', '<>', $id], ['admin_code', '=', $input['adminCode']]])->find();
  54. if (!empty($rs)) {
  55. throw new ApiException('工号不为空');
  56. }
  57. try {
  58. $model->startTrans();
  59. $data = [
  60. 'name' => $input['name'],
  61. 'account' => $input['account'],
  62. 'role_id' => $input['roleId'],
  63. 'mobile' => $input['mobile'],
  64. 'admin_code' => $input['adminCode'],
  65. 'status' => $input['status'] ?? 1,
  66. ];
  67. if (!empty($input['password'])) {
  68. $data['password'] = $this->encodePasswd($input['password']);
  69. }
  70. $model::where(['id' => $id])->update($data);
  71. if(!empty($input['storeIds'])) {
  72. $model->saveStoreRole($input['storeIds'], $id, true);
  73. }
  74. $model->saveGroupRole($input['groupIds'], $id,true);
  75. $model->commit();
  76. }catch (\Exception $e){
  77. $model->rollback();
  78. throw new ApiException($e->getMessage());
  79. }
  80. }
  81. }