CRUD зон/устройств/правил автоматизации + RBAC owner/viewer
Policies (ZonePolicy/DevicePolicy/AutomationRulePolicy): не multi-tenant изоляция по user_id, а household-wide RBAC — все авторизованные видят одни и те же данные, только owner может создавать/менять/удалять. user_id на записи — это created_by, а не граница видимости. Form Requests с authorize() через политики; DeviceRequest учитывает unique external_id с ignore на update. AutomationRuleRequest: action_type остаётся строкой (не enum), т.к. это открытый список из device_types.capabilities; для действия set_level в форме есть отдельное поле "level" (Alpine.js переключает его видимость), которое контроллер мапит в action_params — без сырого JSON-редактора для MVP. Контроллеры без show (index+create/edit достаточно), Blade-формы на базе Breeze-компонентов. Навигация и дашборд (счётчики зон/устройств/активных правил) обновлены. Добавлен DemoGrowboxSeeder (демо-зона с датчиком, вентилятором и правилом) и viewer-пользователь в сидер. Восстановлен трейт AuthorizesRequests в базовом Controller (Laravel 11+ убрал его по умолчанию) — нужен для $this->authorize(). Проверено: 33/33 теста (включая новые ZoneControllerTest, AutomationRuleControllerTest — маппинг level→action_params, 403 для viewer), полный CRUD-цикл вживую через браузер под owner (создание зоны, правила с set_level, Alpine-переключение поля "Уровень"), доступ viewer подтверждён как read-only (нет кнопок изменения, прямой заход на /zones/create отдаёт 403).
This commit is contained in:
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Enums\DeviceCategory;
|
||||
use App\Http\Requests\AutomationRuleRequest;
|
||||
use App\Models\AutomationRule;
|
||||
use App\Models\Device;
|
||||
use App\Models\DeviceType;
|
||||
use App\Models\Zone;
|
||||
|
||||
class AutomationRuleController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$this->authorize('viewAny', AutomationRule::class);
|
||||
|
||||
$rules = AutomationRule::with(['zone', 'targetDevice', 'conditionSourceDevice'])
|
||||
->orderByDesc('id')
|
||||
->get();
|
||||
|
||||
return view('automation-rules.index', ['rules' => $rules]);
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
$this->authorize('create', AutomationRule::class);
|
||||
|
||||
return view('automation-rules.create', $this->formOptions());
|
||||
}
|
||||
|
||||
public function store(AutomationRuleRequest $request)
|
||||
{
|
||||
$rule = new AutomationRule($this->mapActionParams($request->validated()));
|
||||
$rule->user()->associate($request->user());
|
||||
$rule->save();
|
||||
|
||||
return redirect()->route('automation-rules.index')->with('status', 'Правило создано.');
|
||||
}
|
||||
|
||||
public function edit(AutomationRule $automation_rule)
|
||||
{
|
||||
$this->authorize('update', $automation_rule);
|
||||
|
||||
return view('automation-rules.edit', [
|
||||
'rule' => $automation_rule,
|
||||
...$this->formOptions(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function update(AutomationRuleRequest $request, AutomationRule $automation_rule)
|
||||
{
|
||||
$automation_rule->update($this->mapActionParams($request->validated()));
|
||||
|
||||
return redirect()->route('automation-rules.index')->with('status', 'Правило обновлено.');
|
||||
}
|
||||
|
||||
public function destroy(AutomationRule $automation_rule)
|
||||
{
|
||||
$this->authorize('delete', $automation_rule);
|
||||
|
||||
$automation_rule->delete();
|
||||
|
||||
return redirect()->route('automation-rules.index')->with('status', 'Правило удалено.');
|
||||
}
|
||||
|
||||
/**
|
||||
* The "level" form field is a friendlier stand-in for action_params —
|
||||
* only set_level currently takes a parameter, so there's no need for a
|
||||
* raw JSON editor yet.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function mapActionParams(array $data): array
|
||||
{
|
||||
$data['action_params'] = $data['action_type'] === 'set_level'
|
||||
? ['level' => $data['level']]
|
||||
: [];
|
||||
|
||||
unset($data['level']);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function formOptions(): array
|
||||
{
|
||||
$devices = Device::with(['zone', 'deviceType'])->orderBy('name')->get();
|
||||
|
||||
return [
|
||||
'zones' => Zone::orderBy('name')->get(),
|
||||
'devices' => $devices,
|
||||
'actionTypeOptions' => $this->capabilityOptions(DeviceCategory::Actuator),
|
||||
'sensorTypeOptions' => $this->capabilityOptions(DeviceCategory::Sensor),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Distinct capability values across device_types of the given category —
|
||||
* used as friendly select/datalist suggestions, not a hardcoded list.
|
||||
*
|
||||
* @return \Illuminate\Support\Collection<int, string>
|
||||
*/
|
||||
private function capabilityOptions(DeviceCategory $category)
|
||||
{
|
||||
return DeviceType::where('category', $category)
|
||||
->get()
|
||||
->pluck('capabilities')
|
||||
->flatten()
|
||||
->unique()
|
||||
->sort()
|
||||
->values();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user