feat: scope notification storage by partner ID and implement order history view

This commit is contained in:
Suherdy Yacob 2026-06-14 16:08:16 +07:00
parent 82cc2534bc
commit 4e6ce85953
6 changed files with 185 additions and 58 deletions

View File

@ -70,9 +70,6 @@ class _AccountScreenState extends State<AccountScreen> {
void _logout() async { void _logout() async {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
await prefs.remove('odoo_session'); await prefs.remove('odoo_session');
await prefs.remove('last_seen_notification_id');
await prefs.remove('last_device_notified_id');
await prefs.remove('read_notification_ids');
await NotificationService().clearBadge(); await NotificationService().clearBadge();
if (mounted) { if (mounted) {
Navigator.of(context).pushAndRemoveUntil( Navigator.of(context).pushAndRemoveUntil(

View File

@ -24,8 +24,6 @@ class _MainShellState extends State<MainShell> {
int _unreadNotificationCount = 0; int _unreadNotificationCount = 0;
Timer? _notificationTimer; Timer? _notificationTimer;
static const _kLastNotified = 'last_device_notified_id';
late final List<Widget> _pages; late final List<Widget> _pages;
@override @override
@ -69,13 +67,17 @@ class _MainShellState extends State<MainShell> {
if (response != null && response['status'] == 'success') { if (response != null && response['status'] == 'success') {
final List<dynamic> notifs = response['data'] ?? []; final List<dynamic> notifs = response['data'] ?? [];
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
final lastNotifiedId = prefs.getInt(_kLastNotified) ?? 0; final partnerId = widget.partnerId;
final readIds = prefs.getStringList('read_notification_ids'); final keyLastNotified = 'last_device_notified_id_$partnerId';
final keyReadNotificationIds = 'read_notification_ids_$partnerId';
final lastNotifiedId = prefs.getInt(keyLastNotified) ?? 0;
final readIds = prefs.getStringList(keyReadNotificationIds);
int unreadCount = 0; int unreadCount = 0;
if (readIds == null) { if (readIds == null) {
final initialRead = notifs.map((n) => (n['id'] as int? ?? 0).toString()).toList(); final initialRead = notifs.map((n) => (n['id'] as int? ?? 0).toString()).toList();
await prefs.setStringList('read_notification_ids', initialRead); await prefs.setStringList(keyReadNotificationIds, initialRead);
unreadCount = 0; unreadCount = 0;
} else { } else {
unreadCount = notifs unreadCount = notifs
@ -102,7 +104,7 @@ class _MainShellState extends State<MainShell> {
body: notif['body'] ?? '', body: notif['body'] ?? '',
); );
} }
await prefs.setInt(_kLastNotified, highestNewId); await prefs.setInt(keyLastNotified, highestNewId);
} }
await NotificationService().setBadge(unreadCount); await NotificationService().setBadge(unreadCount);

View File

@ -37,7 +37,9 @@ class _NotificationsScreenState extends State<NotificationsScreen> {
if (response != null && response['status'] == 'success') { if (response != null && response['status'] == 'success') {
final List<dynamic> fetched = response['data'] ?? []; final List<dynamic> fetched = response['data'] ?? [];
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
final readIds = prefs.getStringList('read_notification_ids') ?? []; final partnerId = OdooService().client?.sessionId?.partnerId ?? 0;
final keyReadNotificationIds = 'read_notification_ids_$partnerId';
final readIds = prefs.getStringList(keyReadNotificationIds) ?? [];
if (mounted) { if (mounted) {
setState(() { setState(() {
@ -100,11 +102,13 @@ class _NotificationsScreenState extends State<NotificationsScreen> {
isUnread: isUnread, isUnread: isUnread,
onTap: () async { onTap: () async {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
final readIds = prefs.getStringList('read_notification_ids') ?? []; final partnerId = OdooService().client?.sessionId?.partnerId ?? 0;
final keyReadNotificationIds = 'read_notification_ids_$partnerId';
final readIds = prefs.getStringList(keyReadNotificationIds) ?? [];
final notifIdStr = (notif['id'] as int? ?? 0).toString(); final notifIdStr = (notif['id'] as int? ?? 0).toString();
if (!readIds.contains(notifIdStr)) { if (!readIds.contains(notifIdStr)) {
readIds.add(notifIdStr); readIds.add(notifIdStr);
await prefs.setStringList('read_notification_ids', readIds); await prefs.setStringList(keyReadNotificationIds, readIds);
// Recalculate and update system badge count // Recalculate and update system badge count
final unreadCount = _notifications final unreadCount = _notifications
@ -113,7 +117,7 @@ class _NotificationsScreenState extends State<NotificationsScreen> {
await NotificationService().setBadge(unreadCount); await NotificationService().setBadge(unreadCount);
} }
if (!mounted) return; if (!context.mounted) return;
await Navigator.push( await Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
@ -121,6 +125,7 @@ class _NotificationsScreenState extends State<NotificationsScreen> {
NotificationDetailScreen(notif: notif), NotificationDetailScreen(notif: notif),
), ),
); );
if (!context.mounted) return;
_fetchNotifications(); _fetchNotifications();
}, },
); );

View File

@ -1,47 +1,171 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../services/odoo_service.dart';
import '../theme/app_theme.dart'; import '../theme/app_theme.dart';
/// Orders tab placeholder screen for future ordering features. class OrdersScreen extends StatefulWidget {
class OrdersScreen extends StatelessWidget {
const OrdersScreen({super.key}); const OrdersScreen({super.key});
@override
State<OrdersScreen> createState() => _OrdersScreenState();
}
class _OrdersScreenState extends State<OrdersScreen> {
List<dynamic> _history = [];
bool _isLoading = true;
@override
void initState() {
super.initState();
_fetchHistory();
}
Future<void> _fetchHistory() async {
if (mounted) setState(() => _isLoading = true);
try {
final history = await OdooService().getOrderHistory();
if (mounted) {
setState(() {
_history = history;
_isLoading = false;
});
}
} catch (e) {
if (mounted) {
setState(() => _isLoading = false);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error loading history: $e')),
);
}
}
}
String _formatDate(String rawDate) {
if (rawDate.isEmpty) return '';
try {
final parsed = DateTime.parse(rawDate);
final months = [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
];
final year = parsed.year;
final month = months[parsed.month - 1];
final day = parsed.day.toString().padLeft(2, '0');
final hour = parsed.hour.toString().padLeft(2, '0');
final minute = parsed.minute.toString().padLeft(2, '0');
return '$day $month $year, $hour:$minute';
} catch (_) {
return rawDate;
}
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Center( final theme = Theme.of(context);
child: Padding(
padding: const EdgeInsets.all(40), if (_isLoading) {
child: Column( return const Scaffold(
mainAxisSize: MainAxisSize.min, body: Center(child: CircularProgressIndicator()),
children: [ );
Container( }
padding: const EdgeInsets.all(28),
decoration: BoxDecoration( return Scaffold(
color: AppTheme.surfaceContainerLow, appBar: AppBar(
shape: BoxShape.circle, title: const Text('Order & Points History'),
),
child: Icon(
Icons.receipt_long_rounded,
size: 56,
color: AppTheme.secondary,
),
),
const SizedBox(height: 28),
Text(
'Orders',
style: Theme.of(context).textTheme.headlineMedium,
),
const SizedBox(height: 12),
Text(
'Online ordering is coming soon!\nStay tuned for updates.',
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
color: AppTheme.onSurfaceVariant,
height: 1.6,
),
textAlign: TextAlign.center,
),
],
),
), ),
body: _history.isEmpty
? Center(
child: Padding(
padding: const EdgeInsets.all(40),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
padding: const EdgeInsets.all(28),
decoration: const BoxDecoration(
color: AppTheme.surfaceContainerLow,
shape: BoxShape.circle,
),
child: const Icon(
Icons.receipt_long_rounded,
size: 56,
color: AppTheme.secondary,
),
),
const SizedBox(height: 28),
Text(
'No Orders Yet',
style: theme.textTheme.headlineMedium,
),
const SizedBox(height: 12),
Text(
'Your order history and points transactions will show up here after you make purchases.',
style: theme.textTheme.bodyLarge?.copyWith(
color: AppTheme.onSurfaceVariant,
height: 1.6,
),
textAlign: TextAlign.center,
),
],
),
),
)
: RefreshIndicator(
onRefresh: _fetchHistory,
child: ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 16),
itemCount: _history.length,
itemBuilder: (context, index) {
final item = _history[index];
final isEarn = item['type'] == 'earn';
final orderRef = item['order_ref'] as String? ?? '';
final rawDate = item['date'] as String? ?? '';
return Card(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
color: AppTheme.surfaceContainerLow,
child: ListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
leading: Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: (isEarn ? const Color(0xFF2E7D32) : const Color(0xFFC62828)).withValues(alpha: 0.1),
shape: BoxShape.circle,
),
child: Icon(
isEarn ? Icons.add_card_rounded : Icons.payment_rounded,
color: isEarn ? const Color(0xFF2E7D32) : const Color(0xFFC62828),
size: 24,
),
),
title: Text(
orderRef.isNotEmpty ? orderRef : 'Point Adjustment',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
color: AppTheme.onSurface,
),
),
subtitle: Padding(
padding: const EdgeInsets.only(top: 6.0),
child: Text(
_formatDate(rawDate),
style: theme.textTheme.bodySmall?.copyWith(
color: AppTheme.onSurfaceVariant,
),
),
),
trailing: Text(
'${isEarn ? '+' : ''}${item['points']} pts',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
color: isEarn ? const Color(0xFF2E7D32) : const Color(0xFFC62828),
fontSize: 16,
),
),
),
);
},
),
),
); );
} }
} }

View File

@ -181,9 +181,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
void _logout() async { void _logout() async {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
await prefs.remove('odoo_session'); await prefs.remove('odoo_session');
await prefs.remove('last_seen_notification_id');
await prefs.remove('last_device_notified_id');
await prefs.remove('read_notification_ids');
await NotificationService().clearBadge(); await NotificationService().clearBadge();
if (mounted) { if (mounted) {
Navigator.of(context).pushAndRemoveUntil( Navigator.of(context).pushAndRemoveUntil(

View File

@ -6,7 +6,6 @@ import 'notification_service.dart';
// NOTE: This key tracks what IDs have been shown as device tray notifications. // NOTE: This key tracks what IDs have been shown as device tray notifications.
// It is separate from 'last_seen_notification_id' (which tracks what the user READ in-app). // It is separate from 'last_seen_notification_id' (which tracks what the user READ in-app).
const String _kLastDeviceNotifiedId = 'last_device_notified_id';
@pragma('vm:entry-point') @pragma('vm:entry-point')
void callbackDispatcher() { void callbackDispatcher() {
@ -20,11 +19,13 @@ void callbackDispatcher() {
return Future.value(true); // Not logged in, nothing to do return Future.value(true); // Not logged in, nothing to do
} }
final lastDeviceNotifiedId = prefs.getInt(_kLastDeviceNotifiedId) ?? 0;
final sessionArgs = json.decode(sessionStr); final sessionArgs = json.decode(sessionStr);
final session = OdooSession.fromJson( final session = OdooSession.fromJson(
Map<String, dynamic>.from(sessionArgs as Map)); Map<String, dynamic>.from(sessionArgs as Map));
final partnerId = session.partnerId;
final keyLastDeviceNotifiedId = 'last_device_notified_id_$partnerId';
final keyReadNotificationIds = 'read_notification_ids_$partnerId';
final client = OdooClient(url, sessionId: session); final client = OdooClient(url, sessionId: session);
final response = await client.callRPC( final response = await client.callRPC(
@ -40,6 +41,7 @@ void callbackDispatcher() {
List<dynamic>.from(response['data'] ?? []); List<dynamic>.from(response['data'] ?? []);
// Filter to only truly new ones not yet shown on device tray // Filter to only truly new ones not yet shown on device tray
final lastDeviceNotifiedId = prefs.getInt(keyLastDeviceNotifiedId) ?? 0;
final newNotifs = notifications final newNotifs = notifications
.where((n) => (n['id'] as int? ?? 0) > lastDeviceNotifiedId) .where((n) => (n['id'] as int? ?? 0) > lastDeviceNotifiedId)
.toList(); .toList();
@ -60,15 +62,15 @@ void callbackDispatcher() {
); );
} }
await prefs.setInt(_kLastDeviceNotifiedId, highestId); await prefs.setInt(keyLastDeviceNotifiedId, highestId);
} }
// Always compute badge count based on read_notification_ids // Always compute badge count based on read_notification_ids
final readIds = prefs.getStringList('read_notification_ids'); final readIds = prefs.getStringList(keyReadNotificationIds);
if (readIds == null) { if (readIds == null) {
// Initialize read list with all currently fetched notifications on first install/run // Initialize read list with all currently fetched notifications on first install/run
final initialRead = notifications.map((n) => (n['id'] as int? ?? 0).toString()).toList(); final initialRead = notifications.map((n) => (n['id'] as int? ?? 0).toString()).toList();
await prefs.setStringList('read_notification_ids', initialRead); await prefs.setStringList(keyReadNotificationIds, initialRead);
await notifService.setBadge(0); await notifService.setBadge(0);
} else { } else {
final unreadCount = notifications final unreadCount = notifications