From 2da339a2b09084472e718f23817ee182e6ffd5a3 Mon Sep 17 00:00:00 2001 From: rzuasti Date: Wed, 27 May 2026 18:24:35 -0400 Subject: [PATCH] Add device detail screen and navigate to it from notifications and devices - New /devices/:macAddress route showing all device fields with Register/Forget actions - Device list items are now tappable; popup menu gains a "View details" item - Notification list items with a linked device are tappable; popup menu gains a "View device" item - Backend: new DB migration adds optional mac_address column to notifications - Device-related notifications (NewDeviceFound, DeviceOnlineAfterTime, DeviceChanged) now store the triggering device's MAC address Co-Authored-By: Claude Sonnet 4.6 --- .../up.sql | 1 + backend/src/db/notifications.rs | 39 +- backend/src/events.rs | 5 + backend/src/model/notifications.rs | 7 +- frontend/lib/devices/device_detail.dart | 369 ++++++++++++++++++ frontend/lib/devices/device_list.dart | 13 +- frontend/lib/model/notification.dart | 7 +- frontend/lib/navigation.dart | 11 + .../lib/notifications/notification_list.dart | 15 +- frontend/lib/utils/oott_api.dart | 20 +- 10 files changed, 472 insertions(+), 15 deletions(-) create mode 100644 backend/database_migrations/02-add_mac_address_to_notifications/up.sql create mode 100644 frontend/lib/devices/device_detail.dart diff --git a/backend/database_migrations/02-add_mac_address_to_notifications/up.sql b/backend/database_migrations/02-add_mac_address_to_notifications/up.sql new file mode 100644 index 0000000..1e42a5a --- /dev/null +++ b/backend/database_migrations/02-add_mac_address_to_notifications/up.sql @@ -0,0 +1 @@ +ALTER TABLE notifications ADD COLUMN mac_address TEXT; diff --git a/backend/src/db/notifications.rs b/backend/src/db/notifications.rs index 45f48df..3bf2f10 100644 --- a/backend/src/db/notifications.rs +++ b/backend/src/db/notifications.rs @@ -14,7 +14,7 @@ pub fn list( let conn = db::get_db_connection(); let mut sql_statement = - "SELECT id, created_on, notification_type, title, body, is_new FROM notifications WHERE 1=1" + "SELECT id, created_on, notification_type, title, body, is_new, mac_address FROM notifications WHERE 1=1" .to_string(); let mut params: Vec = Vec::new(); @@ -53,6 +53,7 @@ pub fn list( title: row.get(3)?, body: row.get(4)?, is_new: row.get(5)?, + mac_address: row.get(6)?, }) })? .collect::>()?; @@ -64,8 +65,8 @@ pub fn insert(notification: Notification) -> Result { let conn = db::get_db_connection(); match conn.execute( - "INSERT INTO notifications (created_on, notification_type, title, body, is_new) VALUES (?1, ?2, ?3, ?4, ?5)", - params![notification.created_on, notification.notification_type, notification.title, notification.body, notification.is_new]) { + "INSERT INTO notifications (created_on, notification_type, title, body, is_new, mac_address) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + params![notification.created_on, notification.notification_type, notification.title, notification.body, notification.is_new, notification.mac_address]) { Ok(_) => { debug!("Notification inserted into database: {}", notification); Ok(conn.last_insert_rowid()) @@ -126,7 +127,7 @@ pub fn read(id: i64) -> Option { let conn = db::get_db_connection(); let result: Result = conn.query_one( - "SELECT id, created_on, notification_type, title, body, is_new FROM notifications WHERE id=?1", + "SELECT id, created_on, notification_type, title, body, is_new, mac_address FROM notifications WHERE id=?1", params![id], |row| { Ok(Notification { @@ -136,6 +137,7 @@ pub fn read(id: i64) -> Option { title: row.get(3)?, body: row.get(4)?, is_new: row.get(5)?, + mac_address: row.get(6)?, }) }, ); @@ -176,6 +178,7 @@ mod tests { "New notification title".to_string(), "New notification body".to_string(), true, + None, )) .unwrap(); @@ -206,6 +209,7 @@ mod tests { "New notification title".to_string(), "New notification body".to_string(), false, + None, )) .unwrap(); @@ -232,6 +236,7 @@ mod tests { "New notification 1".to_string(), "Body 1".to_string(), true, + None, )) .unwrap(); @@ -241,6 +246,7 @@ mod tests { "New notification 2".to_string(), "Body 2".to_string(), true, + None, )) .unwrap(); @@ -275,6 +281,7 @@ mod tests { "New notification title".to_string(), "New notification body".to_string(), true, + None, )) .unwrap(); @@ -306,6 +313,28 @@ mod tests { inserted_notification.body, "New notification body", "Wrong body (should be 'New notification body')" ); + assert_eq!( + inserted_notification.mac_address, None, + "mac_address should be None" + ); + + // Insert and validate notification with mac_address + let mac = "aa:aa:aa:aa:aa:aa".to_string(); + let inserted_id = insert(Notification::new( + Utc::now(), + NotificationType::NewDeviceFound, + "Device found".to_string(), + "Body".to_string(), + true, + Some(mac.clone()), + )) + .unwrap(); + let inserted_notification = read(inserted_id).unwrap(); + assert_eq!( + inserted_notification.mac_address, + Some(mac), + "mac_address should round-trip through insert/read" + ); // Insert and validate notification without title nor body let created_on = Utc::now(); @@ -315,6 +344,7 @@ mod tests { "".to_string(), "".to_string(), false, + None, )) .unwrap(); @@ -398,6 +428,7 @@ mod tests { "New notification title".to_string(), "New notification body".to_string(), true, + None, )) .unwrap(); diff --git a/backend/src/events.rs b/backend/src/events.rs index a808d16..e721c60 100644 --- a/backend/src/events.rs +++ b/backend/src/events.rs @@ -43,6 +43,7 @@ pub fn trigger_new_device(device: Device) -> Result<(), Box> { device.mac_address, device.ipv4_address, device.vendor ), true, + Some(device.mac_address.clone()), ); send_notification(notification)?; @@ -75,6 +76,7 @@ pub fn trigger_existing_device( ))) ), true, + Some(new_device.mac_address.clone()), ); send_notification(notification)?; @@ -97,6 +99,7 @@ pub fn trigger_existing_device( new_device.vendor, ), true, + Some(new_device.mac_address.clone()), ); send_notification(notification)?; @@ -113,6 +116,7 @@ pub fn trigger_existing_device( new_device.ipv4_address, ), true, + Some(new_device.mac_address.clone()), ); send_notification(notification)?; @@ -129,6 +133,7 @@ pub fn trigger_existing_device( new_device.vendor, ), true, + Some(new_device.mac_address.clone()), ); send_notification(notification)?; diff --git a/backend/src/model/notifications.rs b/backend/src/model/notifications.rs index 30fb336..5f88d09 100644 --- a/backend/src/model/notifications.rs +++ b/backend/src/model/notifications.rs @@ -15,6 +15,7 @@ pub struct Notification { pub title: String, pub body: String, pub is_new: bool, + pub mac_address: Option, } impl Notification { @@ -24,6 +25,7 @@ impl Notification { title: String, body: String, is_new: bool, + mac_address: Option, ) -> Self { Self { id: -1, @@ -32,6 +34,7 @@ impl Notification { title, body, is_new, + mac_address, } } } @@ -40,8 +43,8 @@ impl fmt::Display for Notification { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, - "id={}, created_on={}, notification_type={}, is_new={}\ntitle={}\nbody={}", - self.id, self.created_on, self.notification_type, self.is_new, self.title, self.body + "id={}, created_on={}, notification_type={}, is_new={}, mac_address={:?}\ntitle={}\nbody={}", + self.id, self.created_on, self.notification_type, self.is_new, self.mac_address, self.title, self.body ) } } diff --git a/frontend/lib/devices/device_detail.dart b/frontend/lib/devices/device_detail.dart new file mode 100644 index 0000000..939486a --- /dev/null +++ b/frontend/lib/devices/device_detail.dart @@ -0,0 +1,369 @@ +import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; + +import '../model/device.dart'; +import '../utils/friendly_date_formatter.dart'; +import '../utils/oott_api.dart'; +import '../utils/ui_snackbars.dart'; +import '../widgets/status_badge.dart'; + +const _deviceTypes = [ + 'phone', + 'laptop', + 'tablet', + 'server', + 'router', + 'tv', + 'printer', + 'unknown', +]; + +class DeviceDetail extends StatefulWidget { + final String macAddress; + + const DeviceDetail({super.key, required this.macAddress}); + + @override + State createState() => _DeviceDetailState(); +} + +class _DeviceDetailState extends State { + Device? _device; + bool _isLoading = true; + String? _error; + + @override + void initState() { + super.initState(); + _loadDevice(); + } + + Future _loadDevice() async { + setState(() { + _isLoading = _device == null; + _error = null; + }); + try { + final device = await BackendAPI.instance.getDevice(widget.macAddress); + if (!mounted) return; + setState(() { + _device = device; + _isLoading = false; + }); + } catch (e) { + if (!mounted) return; + setState(() { + _error = e.toString(); + _isLoading = false; + }); + } + } + + Future _confirmForget(Device device) async { + final colorScheme = Theme.of(context).colorScheme; + + final confirmed = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Forget Device'), + content: Text( + 'This device will be unregistered and will no longer be linked to ' + '${device.owner}. Are you sure?', + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () => Navigator.of(context).pop(true), + child: Text('Forget', style: TextStyle(color: colorScheme.error)), + ), + ], + ), + ); + + if (confirmed != true || !mounted) return; + + try { + await BackendAPI.instance.forgetDevice(device.macAddress); + if (!mounted) return; + UISnackbars.showSuccess(context, 'Device forgotten'); + _loadDevice(); + } catch (e) { + if (!mounted) return; + UISnackbars.showError(context, 'Failed to forget device: $e'); + } + } + + Future _showRegisterDialog(Device device) async { + final formKey = GlobalKey(); + String owner = ''; + String deviceType = _deviceTypes.contains(device.deviceType) + ? device.deviceType + : 'unknown'; + + final saved = await showDialog( + context: context, + builder: (context) => StatefulBuilder( + builder: (context, setDialogState) => AlertDialog( + title: const Text('Register Device'), + content: Form( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextFormField( + decoration: const InputDecoration(labelText: 'Owner'), + validator: (value) => value == null || value.trim().isEmpty + ? 'Owner is required' + : null, + onSaved: (value) => owner = value?.trim() ?? '', + ), + const SizedBox(height: 16), + InputDecorator( + decoration: const InputDecoration(labelText: 'Device Type'), + child: DropdownButton( + value: deviceType, + isExpanded: true, + underline: const SizedBox(), + items: _deviceTypes + .map((t) => DropdownMenuItem(value: t, child: Text(t))) + .toList(), + onChanged: (value) => + setDialogState(() => deviceType = value ?? deviceType), + ), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () { + if (formKey.currentState?.validate() ?? false) { + formKey.currentState?.save(); + Navigator.of(context).pop(true); + } + }, + child: const Text('Save'), + ), + ], + ), + ), + ); + + if (saved != true || !mounted) return; + + try { + await BackendAPI.instance.registerDevice( + device.macAddress, + owner, + deviceType, + ); + if (!mounted) return; + UISnackbars.showSuccess(context, 'Device registered'); + _loadDevice(); + } catch (e) { + if (!mounted) return; + UISnackbars.showError(context, 'Failed to register device: $e'); + } + } + + IconData _deviceIcon(String deviceType) { + switch (deviceType.toLowerCase()) { + case 'phone': + return Icons.phone_android; + case 'laptop': + return Icons.laptop; + case 'tablet': + return Icons.tablet_android; + case 'server': + return Icons.dns; + case 'router': + return Icons.router; + case 'tv': + return Icons.tv; + case 'printer': + return Icons.print; + default: + return Icons.device_unknown; + } + } + + @override + Widget build(BuildContext context) { + final device = _device; + + return Scaffold( + appBar: AppBar( + title: const Text('Device Details'), + leading: BackButton(onPressed: () => context.pop()), + actions: [ + if (device != null) + PopupMenuButton( + icon: const Icon(Icons.more_vert), + onSelected: (value) async { + if (value == 'forget') { + await _confirmForget(device); + } else if (value == 'register') { + await _showRegisterDialog(device); + } + }, + itemBuilder: (context) => [ + if (device.isRegistered) + const PopupMenuItem(value: 'forget', child: Text('Forget')), + if (!device.isRegistered) + const PopupMenuItem( + value: 'register', + child: Text('Register'), + ), + ], + ), + ], + ), + body: _isLoading + ? const Center(child: CircularProgressIndicator()) + : _error != null + ? Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('Error: $_error'), + const SizedBox(height: 16), + FilledButton( + onPressed: _loadDevice, + child: const Text('Retry'), + ), + ], + ), + ) + : device == null + ? const Center(child: Text('Device not found')) + : SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _DeviceHeader( + device: device, + deviceIcon: _deviceIcon(device.deviceType), + ), + const SizedBox(height: 24), + _DeviceInfoCard(device: device), + ], + ), + ), + ); + } +} + +class _DeviceHeader extends StatelessWidget { + final Device device; + final IconData deviceIcon; + + const _DeviceHeader({required this.device, required this.deviceIcon}); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Row( + children: [ + Icon(deviceIcon, size: 48), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(device.ipv4Address, style: theme.textTheme.headlineSmall), + const SizedBox(height: 4), + if (device.isRegistered) + StatusBadge(label: 'Registered', color: BadgeColor.success) + else + StatusBadge( + label: 'Not registered', + color: BadgeColor.secondary, + ), + ], + ), + ), + ], + ); + } +} + +class _DeviceInfoCard extends StatelessWidget { + final Device device; + + const _DeviceInfoCard({required this.device}); + + @override + Widget build(BuildContext context) { + final formatter = FriendlyDateFormatter(); + + return Card( + child: Column( + children: [ + _InfoRow(label: 'MAC Address', value: device.macAddress), + const Divider(height: 1), + _InfoRow(label: 'IP Address', value: device.ipv4Address), + const Divider(height: 1), + _InfoRow( + label: 'Vendor', + value: device.vendor.isEmpty ? '—' : device.vendor, + ), + const Divider(height: 1), + _InfoRow( + label: 'Last Seen', + value: formatter.format(device.lastSeen), + ), + const Divider(height: 1), + _InfoRow( + label: 'Device Type', + value: device.deviceType.isEmpty || device.deviceType == 'unknown' + ? 'Unknown' + : device.deviceType, + ), + const Divider(height: 1), + _InfoRow( + label: 'Owner', + value: device.owner.isEmpty ? '—' : device.owner, + ), + ], + ), + ); + } +} + +class _InfoRow extends StatelessWidget { + final String label; + final String value; + + const _InfoRow({required this.label, required this.value}); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 120, + child: Text( + label, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ), + Expanded(child: Text(value, style: theme.textTheme.bodyMedium)), + ], + ), + ); + } +} diff --git a/frontend/lib/devices/device_list.dart b/frontend/lib/devices/device_list.dart index f15c859..800be39 100644 --- a/frontend/lib/devices/device_list.dart +++ b/frontend/lib/devices/device_list.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; import '../model/device.dart'; import '../utils/friendly_date_formatter.dart'; @@ -277,6 +278,8 @@ class _DeviceListState extends State { ? null : theme.colorScheme.secondaryContainer, child: ListTile( + onTap: () => + context.push('/devices/${device.macAddress}'), leading: Tooltip( message: device.deviceType.isEmpty || @@ -309,13 +312,21 @@ class _DeviceListState extends State { PopupMenuButton( icon: const Icon(Icons.more_vert), onSelected: (value) async { - if (value == 'forget') { + if (value == 'details') { + context.push( + '/devices/${device.macAddress}', + ); + } else if (value == 'forget') { await _confirmForget(device); } else if (value == 'register') { await _showRegisterDialog(device); } }, itemBuilder: (context) => [ + const PopupMenuItem( + value: 'details', + child: Text('View details'), + ), if (device.isRegistered) const PopupMenuItem( value: 'forget', diff --git a/frontend/lib/model/notification.dart b/frontend/lib/model/notification.dart index 5c5d0df..fc00265 100644 --- a/frontend/lib/model/notification.dart +++ b/frontend/lib/model/notification.dart @@ -7,6 +7,7 @@ class Notification { bool isNew; NotificationType notificationType; DateTime createdOn; + String? macAddress; Notification({ required this.id, @@ -15,6 +16,7 @@ class Notification { required this.notificationType, required this.createdOn, this.isNew = true, + this.macAddress, }); Notification.fromJson(Map json) @@ -25,7 +27,8 @@ class Notification { ), title = json['title'] as String, body = json['body'] as String, - isNew = json['is_new'] as bool; + isNew = json['is_new'] as bool, + macAddress = json['mac_address'] as String?; Notification copyWith({bool? isNew}) => Notification( id: id, @@ -34,6 +37,7 @@ class Notification { notificationType: notificationType, createdOn: createdOn, isNew: isNew ?? this.isNew, + macAddress: macAddress, ); Map toJson() => { @@ -43,5 +47,6 @@ class Notification { 'title': title, 'body': body, 'is_new': isNew, + 'mac_address': macAddress, }; } diff --git a/frontend/lib/navigation.dart b/frontend/lib/navigation.dart index 2d22cfa..1c7f3ae 100644 --- a/frontend/lib/navigation.dart +++ b/frontend/lib/navigation.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:frontend/settings/settings.dart'; import 'package:go_router/go_router.dart'; +import 'devices/device_detail.dart'; import 'devices/device_list.dart'; import 'notifications/notification_list.dart'; import 'utils/pref_utils.dart'; @@ -26,6 +27,16 @@ final GoRouter router = GoRouter( name: 'devices', builder: (context, state) => const DeviceList(), redirect: (context, state) => _redirectToSettings(), + routes: [ + GoRoute( + path: ':macAddress', + name: 'deviceDetail', + builder: (context, state) { + final mac = state.pathParameters['macAddress']!; + return DeviceDetail(macAddress: mac); + }, + ), + ], ), GoRoute( path: '/settings', diff --git a/frontend/lib/notifications/notification_list.dart b/frontend/lib/notifications/notification_list.dart index eb4cdd9..eab91ba 100644 --- a/frontend/lib/notifications/notification_list.dart +++ b/frontend/lib/notifications/notification_list.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart'; import '../model/notification.dart' as oott_model; @@ -207,13 +208,20 @@ class _NotificationListState extends State { trailing: PopupMenuButton( icon: const Icon(Icons.more_vert), onSelected: (value) async { - if (value == 'mark_read') { + if (value == 'view_device') { + context.push('/devices/${item.macAddress}'); + } else if (value == 'mark_read') { await _markAsRead(context, item); } else if (value == 'mark_new') { await _markAsNew(context, item); } }, itemBuilder: (context) => [ + if (item.macAddress != null) + const PopupMenuItem( + value: 'view_device', + child: Text('View device'), + ), if (item.isNew) const PopupMenuItem( value: 'mark_read', @@ -226,7 +234,10 @@ class _NotificationListState extends State { ), ], ), - onTap: () {}, + onTap: item.macAddress != null + ? () => + context.push('/devices/${item.macAddress}') + : null, isThreeLine: true, ), ), diff --git a/frontend/lib/utils/oott_api.dart b/frontend/lib/utils/oott_api.dart index dbafede..33d7231 100644 --- a/frontend/lib/utils/oott_api.dart +++ b/frontend/lib/utils/oott_api.dart @@ -83,6 +83,13 @@ class BackendAPI { await _dio.post('/notifications/mark_all_as_old'); } + Future getDevice(String macAddress) async { + debugPrint('About to call GET /devices/$macAddress'); + final response = await _dio.get('/devices/$macAddress'); + debugPrint('Received: ${response.data}'); + return Device.fromJson(response.data as Map); + } + Future> listDevices({bool? isRegistered}) async { debugPrint('About to call /devices'); @@ -104,11 +111,14 @@ class BackendAPI { String deviceType, ) async { debugPrint('About to call PUT /devices'); - await _dio.put('/devices', data: { - 'mac_address': macAddress, - 'owner': owner, - 'device_type': deviceType, - }); + await _dio.put( + '/devices', + data: { + 'mac_address': macAddress, + 'owner': owner, + 'device_type': deviceType, + }, + ); } Future forgetDevice(String macAddress) async {