/ app / Http / Livewire / Users / Update.php
Update.php
  1  <?php
  2  
  3  namespace App\Http\Livewire\Users;
  4  
  5  use App\Enums\UserTypeEnum;
  6  use App\Http\Services\UserService;
  7  use App\Models\Entity;
  8  use App\Models\EntityType;
  9  use App\Rules\UniqueAliasForUserType;
 10  use Exception;
 11  use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
 12  use Illuminate\Validation\Rule;
 13  use Livewire\Component;
 14  use Spatie\Permission\Models\Role;
 15  use WireUi\Traits\Actions;
 16  
 17  class Update extends Component
 18  {
 19      use AuthorizesRequests;
 20      use Actions;
 21  
 22      public int $entityId;
 23  
 24      public $roles = [];
 25  
 26      public $entities = [];
 27  
 28      public $relation = [
 29          'entity_id' => null,
 30          'entity_type_id' => null,
 31          'role_ids' => [],
 32          'is_poc' => false,
 33      ];
 34  
 35      public $user = [
 36          'user_type_id' => null,
 37          'alias' => null,
 38          'name' => '',
 39          'lastname' => '',
 40          'username' => '',
 41          'email' => '',
 42          'phone' => '',
 43          'password' => null,
 44          'address' => '',
 45          'internal_identification_number' => '',
 46          'personal_identification_number' => '',
 47          'can_access_inbox' => false,
 48          'can_access_sgoc' => false,
 49      ];
 50  
 51      protected array $rules = [];
 52  
 53      public function rules()
 54      {
 55          return [
 56              'user.user_type_id' => 'required',
 57              'user.alias' => ['nullable', new UniqueAliasForUserType($this->entityId, $this->user['user_type_id'])],
 58              'user.name' => 'required',
 59              'user.lastname' => 'required_if:user.user_type_id,2',
 60              'user.username' => 'required|string|min:2|max:255|unique:users,username,' . $this->entityId,
 61              'user.email' => 'required|email:rfc',
 62              'user.phone' => 'nullable',
 63              'user.password' => 'nullable|min:12',
 64              'user.address' => 'nullable',
 65              'user.internal_identification_number' => 'required_if:user.user_type_id,1',
 66              'user.personal_identification_number' => ['required_if:user.user_type_id,2', Rule::unique('users', 'personal_identification_number')->ignore($this->entityId)->withoutTrashed()->whereNotNull('personal_identification_number')],
 67              'relation.role_ids' => 'required',
 68              'relation.entity_type_id' => 'required_if:user.user_type_id,2',
 69              'relation.entity_id' => 'required_if:user.user_type_id,2',
 70              'relation.is_poc' => 'required|boolean',
 71              'user.can_access_inbox' => 'required',
 72              'user.can_access_sgoc' => 'required',
 73          ];
 74      }
 75  
 76      public function fetchData()
 77      {
 78          $user = UserService::find($this->entityId);
 79  
 80          $this->user = [
 81              'user_type_id' => $user['user_type_id'],
 82              'alias' => $user->getAttribute('alias'),
 83              'name' => $user->getAttribute('name'),
 84              'lastname' => $user['lastname'],
 85              'username' => $user['username'],
 86              'email' => $user['email'],
 87              'phone' => $user['phone'],
 88              'address' => $user['address'],
 89              'internal_identification_number' => $user['internal_identification_number'],
 90              'personal_identification_number' => $user['personal_identification_number'],
 91              'can_access_inbox' => $user['can_access_inbox'],
 92              'can_access_sgoc' => $user['can_access_sgoc'],
 93          ];
 94  
 95          $this->getConfig($user['user_type_id']);
 96  
 97          if ($user->entity()) {
 98              $this->loadEntities($user->entity()->entity_type_id);
 99  
100              $this->relation = [
101                  'entity_id' => $user->entity()->pivot->entity_id,
102                  'entity_type_id' => $user->entity()->entity_type_id,
103                  'is_poc' => $user->entity()->pivot->is_poc ?? false,
104              ];
105          }
106  
107          $this->relation['role_ids'] = $user->roles()->pluck('roles.id') ?? null;
108      }
109  
110      public function mount()
111      {
112          $this->authorize('can_write_users');
113          $this->fetchData();
114          $this->rules = $this->rules();
115      }
116  
117      public function updated($propertyName)
118      {
119          $this->validateOnly($propertyName);
120      }
121  
122      public function updating($field, $value)
123      {
124          match ($field) {
125              'user.user_type_id' => $this->getConfig($value),
126              'relation.entity_type_id' => $this->loadEntities($value),
127              default => null,
128          };
129      }
130  
131      public function getRoles($scope)
132      {
133          $this->roles = Role::where('scope', $scope)
134              ->get()
135              ->map(function ($role) {
136                  return [
137                      'id' => $role->id,
138                      'name' => __('roles.' . $role->name),
139                  ];
140              });
141      }
142  
143      public function getTypesProperty()
144      {
145          return EntityType::get()
146              ->map(function ($entityType) {
147                  return [
148                      'id' => $entityType->id,
149                      'name' => __('entities.type.' . $entityType->name),
150                  ];
151              });
152      }
153  
154      // Own functions
155      public function getConfig($field)
156      {
157          if ($field == UserTypeEnum::INTERNAL->value) {
158              // Reset entities
159              $this->relation['entity'] = null;
160              $this->relation['entity_type_id'] = null;
161              $this->relation['role_ids'] = [];
162  
163              // Get only internal roles
164              $this->getRoles('global');
165          } else {
166              $this->user['internal_identification_number'] = null;
167              $this->relation['role_ids'] = [];
168  
169              // Get only external roles
170              $this->getRoles('entity');
171          }
172      }
173  
174      public function loadEntities($entityTypeId)
175      {
176          $this->relation['entity_id'] = null;
177          $this->entities = Entity::where('entity_type_id', $entityTypeId)->get(['id', 'name'])->toArray();
178      }
179  
180      public function update()
181      {
182          $this->authorize('can_write_users');
183          $this->validate(); //  error al actualizar en el inbox en develop
184  
185          try {
186              $data = [
187                  'user' => $this->user,
188                  'relation' => $this->relation,
189              ];
190  
191              UserService::update($data, $this->entityId);
192  
193              $this->success();
194          } catch (Exception $e) {
195              $this->notification()->error('Error', $e->getMessage());
196              logger()->error($e);
197          }
198      }
199  
200      public function success()
201      {
202          custom_sleep(); // UI Trick for delaying spinner
203  
204          $this->emitUp('closePanel');
205          $this->emitTo('users.index', 'refresh');
206          $this->emitTo('users.view', 'refresh');
207  
208          $this->notification()->success(
209              __('users.notifications.update.success.title'),
210              __('users.notifications.update.success.message')
211          );
212      }
213  
214      public function render()
215      {
216          return view('livewire.users.update');
217      }
218  }