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

153 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/device.dart';
import '../widgets/status_badge.dart';
import 'device_detail_screen.dart';
import 'device_form_screen.dart';
class DevicesTab extends StatefulWidget {
const DevicesTab({super.key});
@override
State<DevicesTab> createState() => _DevicesTabState();
}
class _DevicesTabState extends State<DevicesTab> {
late Future<List<Device>> _future;
@override
void initState() {
super.initState();
_future = _load();
}
Future<List<Device>> _load() => context.read<ApiService>().devices();
Future<void> _refresh() async {
final future = _load();
setState(() => _future = future);
await future;
}
Future<void> _openForm({Device? device}) async {
final saved = await Navigator.of(context).push<bool>(
MaterialPageRoute(builder: (_) => DeviceFormScreen(device: device)),
);
if (saved == true) _refresh();
}
Future<void> _delete(Device device) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Удалить устройство?'),
content: Text(${device.name}» будет удалено без возможности восстановления.'),
actions: [
TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Отмена')),
TextButton(onPressed: () => Navigator.pop(context, true), child: const Text('Удалить')),
],
),
);
if (confirmed != true || !mounted) return;
try {
await context.read<ApiService>().deleteDevice(device.id);
_refresh();
} catch (e) {
if (mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('$e')));
}
}
@override
Widget build(BuildContext context) {
final isOwner = context.watch<AuthService>().user?.isOwner ?? false;
return Scaffold(
body: RefreshIndicator(
onRefresh: _refresh,
child: FutureBuilder<List<Device>>(
future: _future,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return _ErrorList(message: '${snapshot.error}', onRetry: _refresh);
}
final devices = snapshot.data!;
if (devices.isEmpty) {
return _ErrorList(message: 'Устройств пока нет.', onRetry: _refresh);
}
return ListView.separated(
physics: const AlwaysScrollableScrollPhysics(),
itemCount: devices.length,
separatorBuilder: (context, index) => const Divider(height: 1),
itemBuilder: (context, index) {
final device = devices[index];
return ListTile(
title: Text(device.name),
subtitle: Text('${device.zone?.name ?? '—'} · ${device.deviceType?.code ?? device.protocol}'),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
StatusBadge(status: device.status),
if (isOwner)
PopupMenuButton<String>(
onSelected: (value) {
if (value == 'edit') _openForm(device: device);
if (value == 'delete') _delete(device);
},
itemBuilder: (context) => const [
PopupMenuItem(value: 'edit', child: Text('Редактировать')),
PopupMenuItem(value: 'delete', child: Text('Удалить')),
],
),
],
),
onTap: () => Navigator.of(context).push(
MaterialPageRoute(builder: (_) => DeviceDetailScreen(deviceId: device.id)),
),
);
},
);
},
),
),
floatingActionButton: isOwner
? FloatingActionButton(onPressed: () => _openForm(), child: const Icon(Icons.add))
: null,
);
}
}
class _ErrorList extends StatelessWidget {
const _ErrorList({required this.message, required this.onRetry});
final String message;
final Future<void> Function() onRetry;
@override
Widget build(BuildContext context) {
return ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: [
Padding(
padding: const EdgeInsets.symmetric(vertical: 64, horizontal: 24),
child: Column(
children: [
Text(message, textAlign: TextAlign.center),
const SizedBox(height: 12),
TextButton(onPressed: onRetry, child: const Text('Повторить')),
],
),
),
],
);
}
}