Filters working on notifications

This commit is contained in:
rzuasti
2026-03-04 16:22:00 -05:00
parent 63ac1d04d5
commit b8db6db83b
5 changed files with 161 additions and 70 deletions
+37 -14
View File
@@ -6,6 +6,7 @@ use rusqlite::{params, params_from_iter};
use crate::model::notifications::Notification;
pub fn list(
is_new: Option<bool>,
page_offset: Option<i64>,
page_limit: Option<i64>,
) -> Result<Vec<Notification>, DbError> {
@@ -13,12 +14,23 @@ pub fn list(
let conn = db::get_db_connection();
let mut sql_statement =
"SELECT id, created_on, notification_type, title, body FROM notifications WHERE is_new=1"
"SELECT id, created_on, notification_type, title, body, is_new FROM notifications WHERE 1=1"
.to_string();
let mut params: Vec<rusqlite::types::Value> = Vec::new();
// Filters
if is_new.is_some() {
debug!("Adding filter is_new={}", is_new.unwrap());
sql_statement.push_str(" AND is_new=?");
params.push(is_new.unwrap().into());
}
// List order
sql_statement.push_str(" ORDER BY created_on DESC");
let mut params: Vec<rusqlite::types::Value> = Vec::new();
// Paging
if page_offset.is_some() && page_limit.is_some() {
debug!(
"Adding paging to list with offset={} and limit={}",
@@ -41,7 +53,7 @@ pub fn list(
notification_type: row.get(2)?,
title: row.get(3)?,
body: row.get(4)?,
is_new: true,
is_new: row.get(5)?,
})
})?
.collect::<Result<_, _>>()?;
@@ -322,7 +334,7 @@ mod tests {
#[tokio::test]
async fn test_list() {
tests_common::setup().await;
let notifications = list(None, None).unwrap();
let notifications = list(Some(true), None, None).unwrap();
// There should be at least 3 unread notifications
assert!(
@@ -408,12 +420,31 @@ mod tests {
);
}
#[tokio::test]
async fn test_list_filters() {
tests_common::setup().await;
// List only new notifications
let notifications = list(Some(true), Some(0), Some(5)).unwrap();
assert!(
!notifications.iter().any(|item| !item.is_new),
"All notifications should be new"
);
// List only old notifications
let notifications = list(Some(false), Some(0), Some(5)).unwrap();
assert!(
!notifications.iter().any(|item| item.is_new),
"All notifications should be old"
);
}
#[tokio::test]
async fn test_list_pagination() {
tests_common::setup().await;
// List first page with 2 elements
let first_page = list(Some(0), Some(2)).unwrap();
let first_page = list(Some(true), Some(0), Some(2)).unwrap();
assert_eq!(
first_page.iter().len(),
@@ -422,18 +453,10 @@ mod tests {
);
// List second page with 2 elements, should only be 1
let second_page = list(Some(2), Some(2)).unwrap();
let second_page = list(Some(true), Some(2), Some(2)).unwrap();
assert!(
second_page.iter().len() >= 1,
"Second page should have at least 1 notification"
);
// None of the first page elements should be present
for item in first_page.iter() {
assert!(
!second_page.iter().any(|second_item| item == second_item),
"No first page element should be in the second page"
);
}
}
}
+2 -1
View File
@@ -34,10 +34,11 @@ pub async fn read_without_flagging(Path(id): Path<i64>) -> Result<Json<Notificat
pub async fn list(
Query(params): Query<HashMap<String, String>>,
) -> Result<Json<Vec<Notification>>, StatusCode> {
let is_new: Option<bool> = utils::parse_parameter_bool(&params, "is_new");
let page_offset: Option<i64> = utils::parse_parameter_int(&params, "page_offset");
let page_limit: Option<i64> = utils::parse_parameter_int(&params, "page_limit");
match db::notifications::list(page_offset, page_limit) {
match db::notifications::list(is_new, page_offset, page_limit) {
Ok(value) => Ok(Json(value)),
Err(err) => {
error!("Error listing notifications: {}", err);
+2 -2
View File
@@ -9,13 +9,13 @@ enum NotificationType {
IconData get icon {
switch (this) {
case newDeviceFound:
return Icons.devices;
return Icons.radar;
case deviceOnlineAfterTime:
return Icons.timer;
case deviceChanged:
return Icons.change_circle;
case other:
return Icons.priority_high;
return Icons.notification_important;
}
}
@@ -13,32 +13,79 @@ class NotificationList extends StatefulWidget {
}
class _NotificationListState extends State<NotificationList> {
final _pagingController = PagingController<int, oott_model.Notification>(
int _filterChoice = 1; // 1 => Only new, 2=> Only old, 3=> All
late final _pagingController = PagingController<int, oott_model.Notification>(
getNextPageKey: (state) => state.lastPageIsEmpty
? null
: (state.items == null ? 0 : state.items?.length),
fetchPage: (pageKey) => BackendAPI.instance.listNotifications(pageKey),
);
fetchPage: (pageKey) {
bool? isNew;
@override
void dispose() {
_pagingController.dispose();
super.dispose();
if (_filterChoice == 1) {
isNew = true;
} else if (_filterChoice == 2) {
isNew = false;
}
return BackendAPI.instance.listNotifications(isNew, pageKey);
},
);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Notifications')),
body: PagingListener(
body:
// Paginated list start
PagingListener(
controller: _pagingController,
builder: (context, state, fetchNextPage) =>
PagedListView<int, oott_model.Notification>(
builder: (context, state, fetchNextPage) => CustomScrollView(
slivers: [
// Filters go here
SliverToBoxAdapter(
child: Container(
height: 50,
alignment: Alignment.centerRight,
child: Wrap(
spacing: 8.0,
children: [
ChoiceChip(
label: Text('New'),
selected: _filterChoice == 1,
onSelected: (bool selected) {
_filterChoice = 1;
_pagingController.refresh();
},
),
ChoiceChip(
label: Text('Old'),
selected: _filterChoice == 2,
onSelected: (bool selected) {
_filterChoice = 2;
_pagingController.refresh();
},
),
ChoiceChip(
label: Text('All'),
selected: _filterChoice == 3,
onSelected: (bool selected) {
_filterChoice = 3;
_pagingController.refresh();
},
),
],
),
),
),
PagedSliverList<int, oott_model.Notification>(
state: state,
fetchNextPage: fetchNextPage,
builderDelegate: PagedChildBuilderDelegate(
itemBuilder: (context, item, index) {
return Dismissible(
return Column(
children: [
Dismissible(
key: UniqueKey(),
onDismissed: (direction) {
setState(() {
@@ -54,24 +101,40 @@ class _NotificationListState extends State<NotificationList> {
);
},
background: Container(
color: Theme.of(context).colorScheme.primaryContainer,
color: Theme.of(
context,
).colorScheme.primaryContainer,
alignment: Alignment.center,
child: Icon(Icons.done),
),
child: ListTile(
// tileColor: item.isNew ? Colors.amber : null,
leading: Icon(item.notificationType.icon),
title: Text(
'${FriendlyDateFormatter().format(item.createdOn)} - ${item.title}',
),
subtitle: Text(item.body),
subtitle: Text(item.body, maxLines: 5),
trailing: Icon(Icons.more_vert),
onTap: () {},
isThreeLine: true,
),
),
Divider(),
],
);
},
),
),
],
),
),
);
// Paginated list end
}
@override
void dispose() {
_pagingController.dispose();
super.dispose();
}
}
+6 -2
View File
@@ -66,13 +66,17 @@ class BackendAPI {
late String _apiKey;
late Dio _dio;
Future<List<Notification>> listNotifications(int offset) async {
Future<List<Notification>> listNotifications(bool? isNew, int offset) async {
print('About to call /notifications');
Response response;
response = await _dio.get(
'/notifications',
queryParameters: {'page_offset': offset, 'page_limit': _pageSize},
queryParameters: {
'is_new': isNew ?? '',
'page_offset': offset,
'page_limit': _pageSize,
},
);
print('Received: ' + response.data.toString());