DepartmentScope.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace App\Scopes;
  3. use App\Service\RangeService;
  4. use Illuminate\Database\Eloquent\Builder;
  5. use Illuminate\Database\Eloquent\Model;
  6. use Illuminate\Database\Eloquent\Scope;
  7. //判断所属部门和顶级部门
  8. class DepartmentScope implements Scope
  9. {
  10. public $user = [];
  11. public $search = [];
  12. public function __construct($user = [], $search = [])
  13. {
  14. $this->user = $user;
  15. $this->search = $search;
  16. }
  17. public function apply(Builder $builder, Model $model)
  18. {
  19. //是否所有部门
  20. $is_all_depart = $this->user['is_all_depart'] ?? 0;
  21. //权限范围内的部门
  22. $depart_range = $this->user['depart_range'] ?? [];
  23. //我可见的
  24. $is_see = $this->search['is_see'] ?? 0;
  25. //可见范围方法
  26. $range_function = $this->user['range_function'] ?? "";
  27. $is_function_range = $this->hasMethod(new RangeService(),$range_function);
  28. //顶级部门
  29. $search_depart_id = $this->search['top_depart_id'] ?? 0; //顶级公司
  30. if(empty($search_depart_id)){
  31. //默认进来 自身顶级公司
  32. $top_depart_id = $this->user['depart_top'][0] ?? [];
  33. $top_depart_id = $top_depart_id['depart_id'] ?? 0;
  34. }else{
  35. //查询 顶级公司
  36. $top_depart_id = $search_depart_id;
  37. }
  38. $id = [];
  39. //可见范围 以及单据里面填写人员
  40. if($is_function_range) $id = RangeService::$range_function($this->user,$this->search);
  41. if($is_all_depart){
  42. //所有部门
  43. if(empty($search_depart_id)){
  44. if(! $is_see){
  45. //全部
  46. $builder->whereIn('depart_id', $depart_range);
  47. }else{
  48. $builder->whereIn('id', $id);
  49. }
  50. }else{
  51. if(! $is_see){
  52. //某个分社
  53. $builder->where('top_depart_id', $top_depart_id)
  54. ->whereIn('depart_id', $depart_range);
  55. }else{
  56. $builder->whereIn('id', $id);
  57. }
  58. }
  59. }else{
  60. if(! $is_see){
  61. //某个分社
  62. $builder->where('top_depart_id', $top_depart_id)
  63. ->whereIn('depart_id', $depart_range)
  64. ->orWhereIn('id', $id);
  65. }else{
  66. $builder->whereIn('id', $id);
  67. }
  68. }
  69. if(! empty($this->user['is_search_main'])) $builder->orWhere('is_main', '>',0);
  70. }
  71. function hasMethod($class, $methodName)
  72. {
  73. $reflection = new \ReflectionClass($class);
  74. return $reflection->hasMethod($methodName);
  75. }
  76. }