Merge pull request 'added_unread_allread_notification' (#157) from added_unread_allread_notification into main

Reviewed-on: https://repo.ravanertebat.com/TM/tm_app/pulls/157
This commit is contained in:
a.ghabeli
2025-09-24 08:43:05 +03:30
8 changed files with 227 additions and 105 deletions
@@ -4,7 +4,7 @@ import 'package:tm_app/data/services/notification_service.dart';
class NotificationsRepository { class NotificationsRepository {
NotificationsRepository({required NotificationsService notificationsService}) NotificationsRepository({required NotificationsService notificationsService})
: _notificationsService = notificationsService; : _notificationsService = notificationsService;
final NotificationsService _notificationsService; final NotificationsService _notificationsService;
@@ -12,13 +12,20 @@ class NotificationsRepository {
required int limit, required int limit,
required int offset, required int offset,
}) async { }) async {
return _notificationsService.getNotifications( return _notificationsService.getNotifications(limit: limit, offset: offset);
}
Future<Result<Map<String, dynamic>>> markAllAsRead() async {
return _notificationsService.markAllAsRead();
}
Future<Result<NotificationResponseModel>> getUnreadNotifications({
required int limit,
required int offset,
}) {
return _notificationsService.getUnreadNotifications(
limit: limit, limit: limit,
offset: offset, offset: offset,
); );
} }
Future<Result<NotificationResponseModel>> markAllAsRead() async {
return _notificationsService.markAllAsRead();
}
} }
+4 -3
View File
@@ -7,10 +7,11 @@ class NotificationApi {
static const String markAllAsRead = '/api/v1/notifications'; static const String markAllAsRead = '/api/v1/notifications/mark';
static const String markAsRead = '/api/v1/notifications/mark-as-read'; static const String markAsRead = '/api/v1/notifications/mark-as-read';
static const String tenderApprovalsTender = '/api/v1/notifications'; static const String tenderApprovalsTender = '/api/v1/notifications';
static String getTenderApprovalById({required String tenderId}) { static const String unreadNotifications = '/api/v1/notifications?seen=false';
return '$tenderApprovalsTender/$tenderId'; static String getUnreadNotifications({required int limit, required int offset}) {
return '$unreadNotifications?limit=$limit&offset=$offset';
} }
} }
+18 -5
View File
@@ -1,14 +1,15 @@
// notification_service.dart // notification_service.dart
import 'dart:convert'; import 'dart:convert';
import 'package:tm_app/core/utils/result.dart';
import 'package:tm_app/data/services/api/notification_api.dart'; import 'package:tm_app/data/services/api/notification_api.dart';
import 'package:tm_app/data/services/model/notification__response/notification_response_model.dart'; import 'package:tm_app/data/services/model/notification__response/notification_response_model.dart';
import 'package:tm_app/core/utils/result.dart';
import '../../core/network/network_manager.dart'; import '../../core/network/network_manager.dart';
class NotificationsService { class NotificationsService {
NotificationsService({required NetworkManager networkManager}) NotificationsService({required NetworkManager networkManager})
: _networkManager = networkManager; : _networkManager = networkManager;
final NetworkManager _networkManager; final NetworkManager _networkManager;
Future<Result<NotificationResponseModel>> getNotifications({ Future<Result<NotificationResponseModel>> getNotifications({
@@ -24,11 +25,11 @@ class NotificationsService {
return result; return result;
} }
Future<Result<NotificationResponseModel>> markAllAsRead() async { Future<Result<Map<String, dynamic>>> markAllAsRead() async {
final result = await _networkManager.makeRequest( final result = await _networkManager.makeRequest(
NotificationApi.markAllAsRead, NotificationApi.markAllAsRead,
method: 'POST', method: 'GET',
(json) => NotificationResponseModel.fromJson(json), (json) => json,
); );
return result; return result;
} }
@@ -42,6 +43,18 @@ class NotificationsService {
method: 'POST', method: 'POST',
(json) => NotificationResponseModel.fromJson(json), (json) => NotificationResponseModel.fromJson(json),
data: data, data: data,
);
return result;
}
Future<Result<NotificationResponseModel>> getUnreadNotifications({
required int limit,
required int offset,
}) async {
final result = await _networkManager.makeRequest(
NotificationApi.unreadNotifications,
method: 'GET',
(json) => NotificationResponseModel.fromJson(json),
); );
return result; return result;
} }
+99 -47
View File
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:tm_app/core/utils/app_toast.dart';
import 'package:tm_app/core/utils/result.dart'; import 'package:tm_app/core/utils/result.dart';
import 'package:tm_app/data/repositories/notification_repository.dart'; import 'package:tm_app/data/repositories/notification_repository.dart';
import 'package:tm_app/data/services/model/notification__response/notification_response_model.dart'; import 'package:tm_app/data/services/model/notification__response/notification_response_model.dart';
@@ -10,6 +11,7 @@ class NotificationViewModel with ChangeNotifier {
: _repository = repositoryViewModel { : _repository = repositoryViewModel {
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
getNotifications(); getNotifications();
getUnreadNotifications();
}); });
} }
@@ -29,50 +31,57 @@ class NotificationViewModel with ChangeNotifier {
bool get hasMoreData => _hasMoreData; bool get hasMoreData => _hasMoreData;
int get totalPages => _totalPages; int get totalPages => _totalPages;
NotificationResponseModel? _unreadNotificationResponse;
bool _isUnreadLoading = false;
NotificationResponseModel? get unreadNotificationResponse =>
_unreadNotificationResponse;
bool get isUnreadLoading => _isUnreadLoading;
/// Fetch notifications /// Fetch notifications
Future<void> getNotifications({int page = 1, bool isMobile = false}) async { Future<void> getNotifications({int page = 1, bool isMobile = false}) async {
_isLoading = true; _isLoading = true;
notifyListeners(); notifyListeners();
final int offset = _pageSize * page; final int offset = _pageSize * page;
final result = await _repository.getNotifications( final result = await _repository.getNotifications(
limit: _pageSize, limit: _pageSize,
offset: offset, offset: offset,
); );
switch (result) { switch (result) {
case Ok<NotificationResponseModel>(): case Ok<NotificationResponseModel>():
if (isMobile && page > 1) { if (isMobile && page > 1) {
final oldNotifications = final oldNotifications =
_notificationResponseModel?.data?.notifications ?? []; _notificationResponseModel?.data?.notifications ?? [];
final newNotifications = result.value.data?.notifications ?? []; final newNotifications = result.value.data?.notifications ?? [];
_notificationResponseModel = result.value.copyWith( _notificationResponseModel = result.value.copyWith(
data: result.value.data?.copyWith( data: result.value.data?.copyWith(
notifications: [...oldNotifications, ...newNotifications], notifications: [...oldNotifications, ...newNotifications],
), ),
); );
} else { } else {
_notificationResponseModel = result.value; _notificationResponseModel = result.value;
} }
currentPage = page; currentPage = page;
_hasMoreData = _hasMoreData =
(result.value.data?.notifications?.length ?? 0) >= _pageSize; (result.value.data?.notifications?.length ?? 0) >= _pageSize;
_totalPages = result.value.data?.meta?.pages ?? 1; _totalPages = result.value.data?.meta?.pages ?? 1;
break; break;
case Error<NotificationResponseModel>(): case Error<NotificationResponseModel>():
_errorMessage = result.error.toString(); _errorMessage = result.error.toString();
break; break;
}
_isLoading = false;
notifyListeners();
} }
_isLoading = false;
notifyListeners();
}
/// Jump to page /// Jump to page
Future<void> jumpToPage(int page) async { Future<void> jumpToPage(int page) async {
if (_totalPages == 0 || page < 1 || page > _totalPages) { if (_totalPages == 0 || page < 1 || page > _totalPages) {
@@ -82,33 +91,52 @@ Future<void> getNotifications({int page = 1, bool isMobile = false}) async {
} }
/// Mark all as read /// Mark all as read
Future<void> markAllAsRead() async { Future<void> markAllAsRead(BuildContext context) async {
_isLoading = true;
_errorMessage = null; _errorMessage = null;
notifyListeners(); notifyListeners();
final result = await _repository.markAllAsRead(); final result = await _repository.markAllAsRead();
switch (result) { switch (result) {
case Ok<NotificationResponseModel>(): case Ok<Map<String, dynamic>>():
if (_notificationResponseModel?.data?.notifications != null) { final response = result.value;
final updatedNotifications = final success = response['success'] as bool? ?? false;
_notificationResponseModel!.data!.notifications! final message = response['message'] as String? ?? 'Unknown response';
.map((n) => n.copyWith(seen: true))
.toList();
_notificationResponseModel = _notificationResponseModel!.copyWith( if (success) {
data: _notificationResponseModel!.data!.copyWith( if (_notificationResponseModel?.data?.notifications != null) {
notifications: updatedNotifications, final updatedNotifications =
), _notificationResponseModel!.data!.notifications!
); .map((n) => n.copyWith(seen: true))
.toList();
_notificationResponseModel = _notificationResponseModel!.copyWith(
data: _notificationResponseModel!.data!.copyWith(
notifications: updatedNotifications,
),
);
}
await getNotifications(page: currentPage, );
await getUnreadNotifications();
// toast success
AppToast.success(context, 'All notifications marked as read.');
} else {
_errorMessage = message;
AppToast.error(context, message);
} }
break; break;
case Error<NotificationResponseModel>(): case Error<Map<String, dynamic>>():
_errorMessage = result.error.toString(); _errorMessage = result.error.toString();
AppToast.error(context, _errorMessage!);
break; break;
} }
_isLoading = false;
notifyListeners(); notifyListeners();
} }
@@ -129,4 +157,28 @@ Future<void> getNotifications({int page = 1, bool isMobile = false}) async {
return '${difference.inDays} days ago'; return '${difference.inDays} days ago';
} }
} }
Future<void> getUnreadNotifications({int page = 1}) async {
_isUnreadLoading = true;
notifyListeners();
final int offset = _pageSize * page;
final result = await _repository.getUnreadNotifications(
limit: _pageSize,
offset: offset,
);
switch (result) {
case Ok<NotificationResponseModel>():
_unreadNotificationResponse = result.value;
break;
case Error<NotificationResponseModel>():
_errorMessage = result.error.toString();
break;
}
_isUnreadLoading = false;
notifyListeners();
}
} }
@@ -4,12 +4,13 @@ import 'package:tm_app/core/theme/colors.dart';
import 'package:tm_app/core/utils/size_config.dart'; import 'package:tm_app/core/utils/size_config.dart';
import 'package:tm_app/view_models/notification_view_model.dart'; import 'package:tm_app/view_models/notification_view_model.dart';
import 'package:tm_app/views/notification/strings/notification_strings.dart'; import 'package:tm_app/views/notification/strings/notification_strings.dart';
import 'package:tm_app/views/shared/page_selection_dialog.dart';
import 'package:tm_app/views/shared/desktop_navigation_widget.dart'; import 'package:tm_app/views/shared/desktop_navigation_widget.dart';
import 'package:tm_app/views/shared/page_selection_dialog.dart';
import '../../shared/main_tab_bar.dart';
import '../widgets/notification_all_tab.dart'; import '../widgets/notification_all_tab.dart';
import '../widgets/notification_important_tab.dart'; import '../widgets/notification_important_tab.dart';
import '../widgets/notification_unread_tab.dart'; import '../widgets/notification_unread_tab.dart';
import '../../shared/main_tab_bar.dart';
class DesktopNotificationPage extends StatefulWidget { class DesktopNotificationPage extends StatefulWidget {
const DesktopNotificationPage({super.key}); const DesktopNotificationPage({super.key});
@@ -65,7 +66,9 @@ class _DesktopNotificationPageState extends State<DesktopNotificationPage>
child: Align( child: Align(
alignment: Alignment.centerRight, alignment: Alignment.centerRight,
child: InkWell( child: InkWell(
onTap: viewModel.markAllAsRead, onTap: () {
viewModel.markAllAsRead(context);
},
borderRadius: BorderRadius.circular(99), borderRadius: BorderRadius.circular(99),
child: Container( child: Container(
width: 132.0.w(), width: 132.0.w(),
@@ -89,16 +92,27 @@ class _DesktopNotificationPageState extends State<DesktopNotificationPage>
), ),
), ),
SizedBox(height: 12.0.h()), SizedBox(height: 12.0.h()),
Expanded( viewModel.isLoading
child: TabBarView( ? Container()
controller: controller, : Expanded(
children: const [ child: TabBarView(
NotificationAllTab(), controller: controller,
NotificationUnreadTab(), children: const [
NotificationImportantTab(), NotificationAllTab(),
], NotificationUnreadTab(),
NotificationImportantTab(),
],
),
),
if (viewModel.isLoading) ...[
const Spacer(),
const Center(
child: CircularProgressIndicator(
color: AppColors.secondary50,
),
), ),
), const Spacer(),
],
SizedBox(height: 10.0.h()), SizedBox(height: 10.0.h()),
Row( Row(
children: [ children: [
@@ -116,8 +130,10 @@ class _DesktopNotificationPageState extends State<DesktopNotificationPage>
onTap: () async { onTap: () async {
final selectedPage = await showDialog<int>( final selectedPage = await showDialog<int>(
context: context, context: context,
builder: (context) => PageSelectionDialog( builder:
totalPages: viewModel.totalPages), (context) => PageSelectionDialog(
totalPages: viewModel.totalPages,
),
); );
if (selectedPage != null) { if (selectedPage != null) {
@@ -36,7 +36,7 @@ class _MobileNotificationPageState extends State<MobileNotificationPage>
viewModel.hasMoreData) { viewModel.hasMoreData) {
viewModel.getNotifications( viewModel.getNotifications(
page: viewModel.currentPage + 1, page: viewModel.currentPage + 1,
isMobile: true, isMobile: true,
); );
} }
}); });
@@ -51,7 +51,7 @@ class _MobileNotificationPageState extends State<MobileNotificationPage>
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final viewModel = context.watch<NotificationViewModel>(); // ✅ وصل به ویومدل final viewModel = context.watch<NotificationViewModel>();
return Scaffold( return Scaffold(
backgroundColor: AppColors.backgroundColor, backgroundColor: AppColors.backgroundColor,
@@ -72,7 +72,9 @@ class _MobileNotificationPageState extends State<MobileNotificationPage>
child: Align( child: Align(
alignment: Alignment.centerRight, alignment: Alignment.centerRight,
child: InkWell( child: InkWell(
onTap: viewModel.markAllAsRead, // ✅ مثل دسکتاپ/تبلت onTap: () {
viewModel.markAllAsRead(context);
},
borderRadius: BorderRadius.circular(99), borderRadius: BorderRadius.circular(99),
child: Container( child: Container(
width: 132.0.w(), width: 132.0.w(),
@@ -96,20 +98,26 @@ class _MobileNotificationPageState extends State<MobileNotificationPage>
), ),
), ),
SizedBox(height: 12.0.h()), SizedBox(height: 12.0.h()),
Expanded( viewModel.isLoading
child: TabBarView( ? Container()
controller: controller, : Expanded(
children: [ child: TabBarView(
NotificationAllTab(scrollController: _scrollController), controller: controller,
NotificationUnreadTab(scrollController: _scrollController), children: [
NotificationImportantTab(scrollController: _scrollController), NotificationAllTab(scrollController: _scrollController),
], NotificationUnreadTab(scrollController: _scrollController),
), NotificationImportantTab(
), scrollController: _scrollController,
),
],
),
),
if (viewModel.isLoading) ...[ if (viewModel.isLoading) ...[
SizedBox(height: 10.0.h()), const Spacer(),
const Center(child: CircularProgressIndicator()), const Center(
SizedBox(height: 10.0.h()), child: CircularProgressIndicator(color: AppColors.secondary50),
),
const Spacer(),
], ],
], ],
), ),
@@ -70,7 +70,9 @@ class _TabletNotificationPageState extends State<TabletNotificationPage>
child: Align( child: Align(
alignment: Alignment.centerRight, alignment: Alignment.centerRight,
child: InkWell( child: InkWell(
onTap: viewModel.markAllAsRead, onTap: () {
viewModel.markAllAsRead(context);
},
borderRadius: BorderRadius.circular(99), borderRadius: BorderRadius.circular(99),
child: Container( child: Container(
width: 132.0.w(), width: 132.0.w(),
@@ -94,16 +96,27 @@ class _TabletNotificationPageState extends State<TabletNotificationPage>
), ),
), ),
SizedBox(height: 12.0.h()), SizedBox(height: 12.0.h()),
Expanded( viewModel.isLoading
child: TabBarView( ? Container()
controller: controller, : Expanded(
children: const [ child: TabBarView(
NotificationAllTab(), controller: controller,
NotificationUnreadTab(), children: const [
NotificationImportantTab(), NotificationAllTab(),
], NotificationUnreadTab(),
NotificationImportantTab(),
],
),
),
if (viewModel.isLoading) ...[
const Spacer(),
const Center(
child: CircularProgressIndicator(
color: AppColors.secondary50,
),
), ),
), const Spacer(),
],
SizedBox(height: 10.0.h()), SizedBox(height: 10.0.h()),
Row( Row(
children: [ children: [
@@ -121,9 +134,10 @@ class _TabletNotificationPageState extends State<TabletNotificationPage>
onTap: () async { onTap: () async {
final selectedPage = await showDialog<int>( final selectedPage = await showDialog<int>(
context: context, context: context,
builder: (context) => PageSelectionDialog( builder:
totalPages: viewModel.totalPages, (context) => PageSelectionDialog(
), totalPages: viewModel.totalPages,
),
); );
if (selectedPage != null) { if (selectedPage != null) {
@@ -12,9 +12,20 @@ class NotificationUnreadTab extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final viewModel = context.watch<NotificationViewModel>(); final viewModel = context.watch<NotificationViewModel>();
if (viewModel.isUnreadLoading) {
return const Center(child: CircularProgressIndicator());
}
final notifications = final notifications =
viewModel.notificationResponse?.data?.notifications ?? []; viewModel.unreadNotificationResponse?.data?.notifications ?? [];
if (notifications.isEmpty) {
return const Center(child: Text('No unread notifications'));
}
return ListView.builder( return ListView.builder(
controller: scrollController,
itemCount: notifications.length, itemCount: notifications.length,
itemBuilder: (context, index) { itemBuilder: (context, index) {
final notification = notifications[index]; final notification = notifications[index];