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 <noreply@anthropic.com>
This commit is contained in:
rzuasti
2026-05-27 18:24:35 -04:00
co-authored by Claude Sonnet 4.6
parent 07f7d54531
commit 2da339a2b0
10 changed files with 472 additions and 15 deletions
@@ -0,0 +1 @@
ALTER TABLE notifications ADD COLUMN mac_address TEXT;
+35 -4
View File
@@ -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<rusqlite::types::Value> = 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::<Result<_, _>>()?;
@@ -64,8 +65,8 @@ pub fn insert(notification: Notification) -> Result<i64, DbError> {
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<Notification> {
let conn = db::get_db_connection();
let result: Result<Notification, rusqlite::Error> = 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<Notification> {
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();
+5
View File
@@ -43,6 +43,7 @@ pub fn trigger_new_device(device: Device) -> Result<(), Box<dyn Error>> {
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)?;
+5 -2
View File
@@ -15,6 +15,7 @@ pub struct Notification {
pub title: String,
pub body: String,
pub is_new: bool,
pub mac_address: Option<String>,
}
impl Notification {
@@ -24,6 +25,7 @@ impl Notification {
title: String,
body: String,
is_new: bool,
mac_address: Option<String>,
) -> 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
)
}
}
+369
View File
@@ -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<DeviceDetail> createState() => _DeviceDetailState();
}
class _DeviceDetailState extends State<DeviceDetail> {
Device? _device;
bool _isLoading = true;
String? _error;
@override
void initState() {
super.initState();
_loadDevice();
}
Future<void> _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<void> _confirmForget(Device device) async {
final colorScheme = Theme.of(context).colorScheme;
final confirmed = await showDialog<bool>(
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<void> _showRegisterDialog(Device device) async {
final formKey = GlobalKey<FormState>();
String owner = '';
String deviceType = _deviceTypes.contains(device.deviceType)
? device.deviceType
: 'unknown';
final saved = await showDialog<bool>(
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<String>(
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<String>(
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)),
],
),
);
}
}
+12 -1
View File
@@ -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<DeviceList> {
? 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<DeviceList> {
PopupMenuButton<String>(
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',
+6 -1
View File
@@ -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<String, dynamic> 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<String, dynamic> toJson() => {
@@ -43,5 +47,6 @@ class Notification {
'title': title,
'body': body,
'is_new': isNew,
'mac_address': macAddress,
};
}
+11
View File
@@ -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',
@@ -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<NotificationList> {
trailing: PopupMenuButton<String>(
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<NotificationList> {
),
],
),
onTap: () {},
onTap: item.macAddress != null
? () =>
context.push('/devices/${item.macAddress}')
: null,
isThreeLine: true,
),
),
+15 -5
View File
@@ -83,6 +83,13 @@ class BackendAPI {
await _dio.post('/notifications/mark_all_as_old');
}
Future<Device> 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<String, dynamic>);
}
Future<List<Device>> 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<void> forgetDevice(String macAddress) async {