Files
home_automatization/laravel-app/app/Http/Controllers/AutomationRuleController.php
T
cacto be1f238f89 Перевод защищённой части приложения на Vue.js + Inertia
Дашборд, зоны, устройства, правила автоматизации и профиль теперь
Vue 3 + Inertia вместо Blade+Alpine — гостевые страницы Breeze
(логин/регистрация) сознательно оставлены на Blade, чтобы не трогать
уже протестированную аутентификацию. Контроллеры возвращают
Inertia::render() вместо view(), переиспользуют существующие
API Resources и FormRequest.

Ключевой нюанс: Resource/ResourceCollection, переданные напрямую в
проп Inertia, заворачиваются в ключ "data" (Inertia вызывает
toResponse() у Responsable-объектов) — везде используется ->resolve()
и явное резолвление вложенных ресурсов (zone/device_type внутри
Device и т.п.), иначе вложенные поля тоже задваивались бы обёрткой.

Alpine.js и все Blade-вьюхи защищённой части удалены как мёртвый код.
Тесты (ZoneControllerTest/DeviceControllerTest) переведены на
assertInertia(). UserFactory теперь явно задаёт role=owner — без
этого Eloquent не подтягивает DB-default обратно в модель после
create(), что уронило бы общий auth.user проп на любой странице.
2026-08-12 10:52:04 +05:00

138 lines
4.5 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Enums\ConditionOperator;
use App\Enums\DeviceCategory;
use App\Http\Requests\AutomationRuleRequest;
use App\Http\Resources\AutomationRuleResource;
use App\Http\Resources\DeviceResource;
use App\Http\Resources\ZoneResource;
use App\Models\AutomationRule;
use App\Models\Device;
use App\Models\DeviceType;
use App\Models\Zone;
use Illuminate\Support\Collection;
use Inertia\Inertia;
class AutomationRuleController extends Controller
{
public function index()
{
$this->authorize('viewAny', AutomationRule::class);
$rules = AutomationRule::with(['zone', 'targetDevice', 'conditionSourceDevice'])
->orderByDesc('id')
->get();
return Inertia::render('AutomationRules/Index', [
'rules' => AutomationRuleResource::collection($rules)->resolve(),
]);
}
public function create()
{
$this->authorize('create', AutomationRule::class);
return Inertia::render('AutomationRules/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 Inertia::render('AutomationRules/Edit', [
'rule' => [
'id' => $automation_rule->id,
'zone_id' => $automation_rule->zone_id,
'condition_source_device_id' => $automation_rule->condition_source_device_id,
'condition_sensor_type' => $automation_rule->condition_sensor_type,
'condition_operator' => $automation_rule->condition_operator->value,
'condition_value' => $automation_rule->condition_value,
'target_device_id' => $automation_rule->target_device_id,
'action_type' => $automation_rule->action_type,
'level' => $automation_rule->action_params['level'] ?? '',
'is_active' => $automation_rule->is_active,
],
...$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' => ZoneResource::collection(Zone::orderBy('name')->get())->resolve(),
'devices' => DeviceResource::collection($devices)->resolve(),
'actionTypeOptions' => $this->capabilityOptions(DeviceCategory::Actuator),
'sensorTypeOptions' => $this->capabilityOptions(DeviceCategory::Sensor),
'conditionOperatorOptions' => array_map(fn ($case) => $case->value, ConditionOperator::cases()),
];
}
/**
* Distinct capability values across device_types of the given category —
* used as friendly select/datalist suggestions, not a hardcoded list.
*
* @return Collection<int, string>
*/
private function capabilityOptions(DeviceCategory $category)
{
return DeviceType::where('category', $category)
->get()
->pluck('capabilities')
->flatten()
->unique()
->sort()
->values();
}
}