Files
home_automation_mobile/lib/screens/automation_rules_tab.dart
T
cacto f6749cdff0 Формы создания/редактирования зон, устройств и правил автоматизации
ZoneFormScreen/DeviceFormScreen/AutomationRuleFormScreen — одна форма
на создание и редактирование, показ ошибок валидации Laravel (422)
по полям. Списки зон/устройств/правил дополнены FAB "добавить",
свайпом/меню удаления и переходом в форму по тапу — всё только для
owner (RBAC), viewer видит те же списки в режиме только чтения.
Опции дропдаунов (типы устройств, датчики/актуаторы, capabilities)
берутся из данных бэкенда, не хардкодятся.
2026-08-12 09:53:50 +05:00

146 lines
5.1 KiB
Dart

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../core/api_service.dart';
import '../core/auth_service.dart';
import '../models/automation_rule.dart';
import 'automation_rule_form_screen.dart';
class AutomationRulesTab extends StatefulWidget {
const AutomationRulesTab({super.key});
@override
State<AutomationRulesTab> createState() => _AutomationRulesTabState();
}
class _AutomationRulesTabState extends State<AutomationRulesTab> {
late Future<List<AutomationRule>> _future;
@override
void initState() {
super.initState();
_future = _load();
}
Future<List<AutomationRule>> _load() => context.read<ApiService>().automationRules();
Future<void> _refresh() async {
final future = _load();
setState(() => _future = future);
await future;
}
Future<void> _openForm({AutomationRule? rule}) async {
final saved = await Navigator.of(context).push<bool>(
MaterialPageRoute(builder: (_) => AutomationRuleFormScreen(rule: rule)),
);
if (saved == true) _refresh();
}
Future<bool> _confirmDelete(AutomationRule rule) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Удалить правило?'),
content: const Text('Правило будет удалено без возможности восстановления.'),
actions: [
TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Отмена')),
TextButton(onPressed: () => Navigator.pop(context, true), child: const Text('Удалить')),
],
),
);
if (confirmed != true || !mounted) return false;
try {
await context.read<ApiService>().deleteAutomationRule(rule.id);
return true;
} catch (e) {
if (mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('$e')));
return false;
}
}
@override
Widget build(BuildContext context) {
final isOwner = context.watch<AuthService>().user?.isOwner ?? false;
return Scaffold(
body: RefreshIndicator(
onRefresh: _refresh,
child: FutureBuilder<List<AutomationRule>>(
future: _future,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: [
Padding(
padding: const EdgeInsets.all(24),
child: Text('${snapshot.error}', textAlign: TextAlign.center),
),
],
);
}
final rules = snapshot.data!;
if (rules.isEmpty) {
return ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: const [
Padding(
padding: EdgeInsets.all(24),
child: Text('Правил пока нет.', textAlign: TextAlign.center),
),
],
);
}
return ListView.separated(
physics: const AlwaysScrollableScrollPhysics(),
itemCount: rules.length,
separatorBuilder: (context, index) => const Divider(height: 1),
itemBuilder: (context, index) {
final rule = rules[index];
final condition =
'${rule.conditionSourceDevice?.name ?? '?'}: ${rule.conditionSensorType} ${rule.conditionOperator} ${rule.conditionValue}';
final action = rule.level != null
? '${rule.actionType} (${rule.level}) → ${rule.targetDevice?.name ?? '?'}'
: '${rule.actionType}${rule.targetDevice?.name ?? '?'}';
final tile = ListTile(
leading: Icon(rule.isActive ? Icons.bolt : Icons.bolt_outlined),
title: Text('ЕСЛИ $condition'),
subtitle: Text('ТО $action'),
isThreeLine: true,
onTap: isOwner ? () => _openForm(rule: rule) : null,
);
if (!isOwner) return tile;
return Dismissible(
key: ValueKey(rule.id),
direction: DismissDirection.endToStart,
background: Container(
color: Theme.of(context).colorScheme.error,
alignment: Alignment.centerRight,
padding: const EdgeInsets.symmetric(horizontal: 20),
child: const Icon(Icons.delete, color: Colors.white),
),
confirmDismiss: (_) => _confirmDelete(rule),
child: tile,
);
},
);
},
),
),
floatingActionButton: isOwner
? FloatingActionButton(onPressed: () => _openForm(), child: const Icon(Icons.add))
: null,
);
}
}