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 $data * @return array */ private function mapActionParams(array $data): array { $data['action_params'] = $data['action_type'] === 'set_level' ? ['level' => $data['level']] : []; unset($data['level']); return $data; } /** * @return array */ 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 */ private function capabilityOptions(DeviceCategory $category) { return DeviceType::where('category', $category) ->get() ->pluck('capabilities') ->flatten() ->unique() ->sort() ->values(); } }