107 lines
3.1 KiB
PHP
107 lines
3.1 KiB
PHP
<?php
|
|
|
|
namespace App\Livewire\Users;
|
|
|
|
use App\Models\Department;
|
|
use App\Models\User;
|
|
use Illuminate\Support\Facades\Hash;
|
|
use Illuminate\Validation\Rule;
|
|
use Livewire\Attributes\Layout;
|
|
use Livewire\Component;
|
|
|
|
#[Layout('layouts.app')]
|
|
class UserFormPage extends Component
|
|
{
|
|
public ?User $userModel = null;
|
|
|
|
public string $name = '';
|
|
|
|
public string $email = '';
|
|
|
|
public string $password = '';
|
|
|
|
public string $password_confirmation = '';
|
|
|
|
public string $role = 'client';
|
|
|
|
public string $departmentId = '';
|
|
|
|
public string $phone = '';
|
|
|
|
public bool $isActive = true;
|
|
|
|
public function mount(?User $user = null): void
|
|
{
|
|
abort_unless(auth()->user()->isAdmin(), 403);
|
|
|
|
if ($user && $user->exists) {
|
|
$this->userModel = $user;
|
|
$this->name = $user->name;
|
|
$this->email = $user->email;
|
|
$this->role = $user->role->value;
|
|
$this->departmentId = (string) $user->department_id;
|
|
$this->phone = (string) $user->phone;
|
|
$this->isActive = (bool) $user->is_active;
|
|
}
|
|
}
|
|
|
|
public function save()
|
|
{
|
|
$emailRule = Rule::unique('users', 'email');
|
|
if ($this->userModel) {
|
|
$emailRule = $emailRule->ignore($this->userModel->id);
|
|
}
|
|
|
|
$rules = [
|
|
'name' => ['required', 'string', 'max:255'],
|
|
'email' => ['required', 'email', 'max:255', $emailRule],
|
|
'role' => ['required', Rule::in(['admin', 'manager', 'technician', 'client'])],
|
|
'departmentId' => ['nullable', 'exists:departments,id'],
|
|
'phone' => ['nullable', 'string', 'max:32'],
|
|
'isActive' => ['boolean'],
|
|
];
|
|
|
|
if ($this->userModel) {
|
|
$rules['password'] = ['nullable', 'string', 'min:8', 'same:password_confirmation'];
|
|
} else {
|
|
$rules['password'] = ['required', 'string', 'min:8', 'same:password_confirmation'];
|
|
}
|
|
|
|
$this->validate($rules);
|
|
|
|
$payload = [
|
|
'name' => $this->name,
|
|
'email' => $this->email,
|
|
'role' => $this->role,
|
|
'department_id' => $this->departmentId ?: null,
|
|
'phone' => $this->phone,
|
|
'is_active' => $this->isActive,
|
|
];
|
|
|
|
if ($this->password !== '') {
|
|
$payload['password'] = Hash::make($this->password);
|
|
}
|
|
|
|
if ($this->userModel) {
|
|
$this->userModel->update($payload);
|
|
session()->flash('success', 'Пользователь обновлен.');
|
|
|
|
return redirect()->route('users.show', $this->userModel);
|
|
}
|
|
|
|
$payload['password'] = Hash::make($this->password);
|
|
$user = User::query()->create($payload);
|
|
|
|
session()->flash('success', 'Пользователь создан.');
|
|
|
|
return redirect()->route('users.show', $user);
|
|
}
|
|
|
|
public function render()
|
|
{
|
|
return view('livewire.users.user-form-page', [
|
|
'departments' => Department::query()->orderBy('name')->get(),
|
|
])->title($this->userModel ? 'Редактирование пользователя' : 'Создание пользователя');
|
|
}
|
|
}
|