UserService.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace App\Modules\Admin\Services;
  3. use App\Base\BaseService;
  4. use App\Base\Utils;
  5. use App\Exceptions\ClientException;
  6. use App\Models\User\User;
  7. use Illuminate\Database\Eloquent\Builder;
  8. use Illuminate\Support\Arr;
  9. class UserService extends BaseService
  10. {
  11. public function paginate($params)
  12. {
  13. $p = User::query()->with(["group", "company"])->when($params['status'], function (Builder $query) use ($params) {
  14. return $query->where("status", $params['status']);
  15. })->when($params['userinfo'], function (Builder $query) use ($params) {
  16. return $query->where(function (Builder $query) use ($params) {
  17. return $query->where("phone", $params['userinfo'])->orWhere("email", $params['userinfo'])->orWhere("id", $params['userinfo']);
  18. });
  19. })->orderByDesc("id")->paginate($params['page_size']);
  20. return [
  21. "total" => $p->total(),
  22. "page_total" => $p->lastPage(),
  23. "list" => array_map(function (User $u) {
  24. return [
  25. "id" => Utils::idNo4($u->id),
  26. "phone" => $u->phone,
  27. "email" => $u->email,
  28. "status" => $u->status,
  29. "created_at" => $u->created_at->format("Y-m-d"),
  30. "company" => optional($u->company)->name,
  31. "group_id" => $u->group_id,
  32. "group_name" => optional($u->group)->name ?? "",
  33. 'permissions' => Arr::get($u->extra, 'permissions'),
  34. ];
  35. }, $p->items()),
  36. ];
  37. }
  38. public function changeStatus($data)
  39. {
  40. $u = User::findOrFail($data['id']);
  41. if ($u->id == \Auth::id()) {
  42. throw new ClientException("你不能禁用自己的账号");
  43. }
  44. $u->status = $u->status == User::STATUS_OK ? User::STATUS_STOP : User::STATUS_OK;
  45. $u->save();
  46. return true;
  47. }
  48. public function saveSetting($data)
  49. {
  50. $u = User::findOrFail($data['id']);
  51. $u->group_id = $data['group_id'];
  52. if ($data['password']) {
  53. $u->password = $u->hashPassword($data['password']);
  54. }
  55. $u->extra = array_merge($u->extra ?? [], [
  56. "permissions" => $data['permissions'] ?? [],
  57. ]);
  58. $u->save();
  59. return true;
  60. }
  61. }