notification overhaul

This commit is contained in:
2025-08-30 00:12:29 +02:00
parent 9ae2bb5654
commit 6dccac6124
25 changed files with 1313 additions and 3947 deletions

View File

@@ -24,10 +24,7 @@ class SettingsProvider extends ChangeNotifier {
int _nightStart = 23;
int _nightEnd = 4;
// Persistent reminder settings
bool _persistentReminders = true;
int _reminderRetryInterval = 5; // minutes
int _maxRetryAttempts = 3;
// Auto-sync settings
bool _autoSyncEnabled = false;
@@ -58,10 +55,7 @@ class SettingsProvider extends ChangeNotifier {
int get nightStart => _nightStart;
int get nightEnd => _nightEnd;
// Persistent reminder getters
bool get persistentReminders => _persistentReminders;
int get reminderRetryInterval => _reminderRetryInterval;
int get maxRetryAttempts => _maxRetryAttempts;
// Auto-sync getters
bool get autoSyncEnabled => _autoSyncEnabled;
@@ -110,10 +104,7 @@ class SettingsProvider extends ChangeNotifier {
_nightStart = prefs.getInt('night_start') ?? 23;
_nightEnd = prefs.getInt('night_end') ?? 4;
// Load persistent reminder settings
_persistentReminders = prefs.getBool('persistent_reminders') ?? true;
_reminderRetryInterval = prefs.getInt('reminder_retry_interval') ?? 5;
_maxRetryAttempts = prefs.getInt('max_retry_attempts') ?? 3;
// Load auto-sync settings
_autoSyncEnabled = prefs.getBool('auto_sync_enabled') ?? false;
@@ -278,30 +269,7 @@ class SettingsProvider extends ChangeNotifier {
}
}
// Persistent reminder setters
Future<void> setPersistentReminders(bool enabled) async {
_persistentReminders = enabled;
notifyListeners();
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('persistent_reminders', enabled);
}
Future<void> setReminderRetryInterval(int minutes) async {
_reminderRetryInterval = minutes;
notifyListeners();
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('reminder_retry_interval', minutes);
}
Future<void> setMaxRetryAttempts(int attempts) async {
_maxRetryAttempts = attempts;
notifyListeners();
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('max_retry_attempts', attempts);
}
// Auto-sync setters
Future<void> setAutoSyncEnabled(bool enabled) async {

View File

@@ -1,4 +1,5 @@
import 'package:flutter/foundation.dart';
import 'package:supplements/logging.dart';
import '../services/database_sync_service.dart';
import '../services/auto_sync_service.dart';
@@ -66,7 +67,7 @@ class SimpleSyncProvider with ChangeNotifier {
);
if (kDebugMode) {
print('SimpleSyncProvider: Auto-sync service initialized');
printLog('SimpleSyncProvider: Auto-sync service initialized');
}
}
@@ -111,7 +112,7 @@ class SimpleSyncProvider with ChangeNotifier {
await _syncService.syncDatabase();
} catch (e) {
if (kDebugMode) {
print('SupplementsLog: Sync failed in provider: $e');
printLog('Sync failed in provider: $e');
}
rethrow;
} finally {

View File

@@ -3,22 +3,24 @@ import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:supplements/logging.dart';
import '../models/supplement.dart';
import '../models/supplement_intake.dart';
import '../services/database_helper.dart';
import '../services/database_sync_service.dart';
import '../services/notification_service.dart';
import '../services/simple_notification_service.dart';
class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
final DatabaseHelper _databaseHelper = DatabaseHelper.instance;
final NotificationService _notificationService = NotificationService();
final SimpleNotificationService _notificationService = SimpleNotificationService.instance;
bool _initialized = false;
List<Supplement> _supplements = [];
List<Map<String, dynamic>> _todayIntakes = [];
List<Map<String, dynamic>> _monthlyIntakes = [];
bool _isLoading = false;
Timer? _persistentReminderTimer;
Timer? _dateChangeTimer;
DateTime _lastDateCheck = DateTime.now();
@@ -41,37 +43,22 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
}
Future<void> initialize() async {
if (_initialized) {
return;
}
_initialized = true;
// Add this provider as an observer for app lifecycle changes
WidgetsBinding.instance.addObserver(this);
await _notificationService.initialize();
// Set up the callback for handling supplement intake from notifications
print('SupplementsLog: 📱 Setting up notification callback...');
_notificationService.setTakeSupplementCallback((supplementId, supplementName, units, unitType) {
print('SupplementsLog: 📱 === NOTIFICATION CALLBACK TRIGGERED ===');
print('SupplementsLog: 📱 Supplement ID: $supplementId');
print('SupplementsLog: 📱 Supplement Name: $supplementName');
print('SupplementsLog: 📱 Units: $units');
print('SupplementsLog: 📱 Unit Type: $unitType');
// Record the intake when user taps "Take" on notification
recordIntake(supplementId, 0.0, unitsTaken: units);
print('SupplementsLog: 📱 Intake recorded successfully');
print('SupplementsLog: 📱 === CALLBACK COMPLETE ===');
if (kDebugMode) {
print('SupplementsLog: 📱 Recorded intake from notification: $supplementName ($units $unitType)');
}
});
print('SupplementsLog: 📱 Notification callback setup complete');
// Request permissions with error handling
try {
await _notificationService.requestPermissions();
} catch (e) {
if (kDebugMode) {
print('SupplementsLog: Error requesting notification permissions: $e');
printLog('Error requesting notification permissions: $e');
}
// Continue without notifications rather than crashing
}
@@ -79,35 +66,14 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
await loadSupplements();
await loadTodayIntakes();
// Reschedule notifications for all active supplements to ensure persistence
// Schedule notifications for all active supplements
await _rescheduleAllNotifications();
// Start periodic checking for persistent reminders (every 5 minutes)
_startPersistentReminderCheck();
// Start date change monitoring to reset daily intake status
_startDateChangeMonitoring();
}
void _startPersistentReminderCheck() {
// Cancel any existing timer
_persistentReminderTimer?.cancel();
// Check every 5 minutes for persistent reminders
_persistentReminderTimer = Timer.periodic(const Duration(minutes: 5), (timer) async {
try {
// This will be called from settings provider context, so we need to import it
await _checkPersistentReminders();
} catch (e) {
if (kDebugMode) {
print('SupplementsLog: Error checking persistent reminders: $e');
}
}
});
// Also check immediately
_checkPersistentReminders();
}
void _startDateChangeMonitoring() {
// Cancel any existing timer
@@ -121,8 +87,8 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
if (currentDate != lastCheckDate) {
if (kDebugMode) {
print('SupplementsLog: Date changed detected: ${lastCheckDate} -> ${currentDate}');
print('SupplementsLog: Refreshing today\'s intakes for new day...');
printLog('Date changed detected: ${lastCheckDate} -> ${currentDate}');
printLog('Refreshing today\'s intakes for new day...');
}
// Date has changed, refresh today's intakes
@@ -130,49 +96,22 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
await loadTodayIntakes();
if (kDebugMode) {
print('SupplementsLog: Today\'s intakes refreshed for new day');
printLog('Today\'s intakes refreshed for new day');
}
}
});
}
Future<void> _checkPersistentReminders() async {
// This method will be enhanced to accept settings from the UI layer
// For now, we'll check with default settings
// In practice, the UI should call checkPersistentRemindersWithSettings
if (kDebugMode) {
print('SupplementsLog: 📱 Checking persistent reminders with default settings');
}
}
// Method to be called from UI with actual settings
Future<void> checkPersistentRemindersWithSettings({
required bool persistentReminders,
required int reminderRetryInterval,
required int maxRetryAttempts,
}) async {
print('SupplementsLog: 📱 🔄 MANUAL CHECK: Persistent reminders called from UI');
await _notificationService.checkPersistentReminders(
persistentReminders,
reminderRetryInterval,
maxRetryAttempts,
);
}
// Add a manual trigger method for testing
Future<void> triggerRetryCheck() async {
print('SupplementsLog: 📱 🚨 MANUAL TRIGGER: Forcing retry check...');
await checkPersistentRemindersWithSettings(
persistentReminders: true,
reminderRetryInterval: 5, // Force 5 minute interval for testing
maxRetryAttempts: 3,
);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_persistentReminderTimer?.cancel();
_dateChangeTimer?.cancel();
super.dispose();
}
@@ -184,7 +123,7 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
if (state == AppLifecycleState.resumed) {
// App came back to foreground, check if date changed
if (kDebugMode) {
print('SupplementsLog: App resumed, checking for date change...');
printLog('App resumed, checking for date change...');
}
forceCheckDateChange();
}
@@ -192,23 +131,20 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
Future<void> _rescheduleAllNotifications() async {
if (kDebugMode) {
print('SupplementsLog: 📱 Rescheduling notifications for all active supplements...');
printLog('📱 Rescheduling notifications for all active supplements...');
}
for (final supplement in _supplements) {
if (supplement.reminderTimes.isNotEmpty) {
try {
await _notificationService.scheduleSupplementReminders(supplement);
} catch (e) {
if (kDebugMode) {
print('SupplementsLog: 📱 Error rescheduling notifications for ${supplement.name}: $e');
}
}
try {
await _notificationService.scheduleDailyGroupedRemindersSafe(_supplements);
await _notificationService.getPendingNotifications();
} catch (e) {
if (kDebugMode) {
printLog('📱 Error scheduling grouped notifications: $e');
}
}
if (kDebugMode) {
print('SupplementsLog: 📱 Finished rescheduling notifications');
printLog('📱 Finished rescheduling notifications');
}
}
@@ -217,16 +153,16 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
notifyListeners();
try {
print('SupplementsLog: Loading supplements from database...');
printLog('Loading supplements from database...');
_supplements = await _databaseHelper.getAllSupplements();
print('SupplementsLog: Loaded ${_supplements.length} supplements');
printLog('Loaded ${_supplements.length} supplements');
for (var supplement in _supplements) {
print('SupplementsLog: Supplement: ${supplement.name}');
printLog('Supplement: ${supplement.name}');
}
} catch (e) {
print('SupplementsLog: Error loading supplements: $e');
printLog('Error loading supplements: $e');
if (kDebugMode) {
print('SupplementsLog: Error loading supplements: $e');
printLog('Error loading supplements: $e');
}
} finally {
_isLoading = false;
@@ -236,28 +172,23 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
Future<void> addSupplement(Supplement supplement) async {
try {
print('SupplementsLog: Adding supplement: ${supplement.name}');
printLog('Adding supplement: ${supplement.name}');
final id = await _databaseHelper.insertSupplement(supplement);
print('SupplementsLog: Supplement inserted with ID: $id');
printLog('Supplement inserted with ID: $id');
final newSupplement = supplement.copyWith(id: id);
// Schedule notifications (skip if there's an error)
try {
await _notificationService.scheduleSupplementReminders(newSupplement);
print('SupplementsLog: Notifications scheduled');
} catch (notificationError) {
print('SupplementsLog: Warning: Could not schedule notifications: $notificationError');
}
// Notifications will be rescheduled in grouped mode after reloading supplements
await loadSupplements();
print('SupplementsLog: Supplements reloaded, count: ${_supplements.length}');
printLog('Supplements reloaded, count: ${_supplements.length}');
await _rescheduleAllNotifications();
// Trigger sync after adding supplement
_triggerSyncIfEnabled();
} catch (e) {
print('SupplementsLog: Error adding supplement: $e');
printLog('Error adding supplement: $e');
if (kDebugMode) {
print('SupplementsLog: Error adding supplement: $e');
printLog('Error adding supplement: $e');
}
rethrow;
}
@@ -267,16 +198,14 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
try {
await _databaseHelper.updateSupplement(supplement);
// Reschedule notifications
await _notificationService.scheduleSupplementReminders(supplement);
await loadSupplements();
await _rescheduleAllNotifications();
// Trigger sync after updating supplement
_triggerSyncIfEnabled();
} catch (e) {
if (kDebugMode) {
print('SupplementsLog: Error updating supplement: $e');
printLog('Error updating supplement: $e');
}
}
}
@@ -298,7 +227,7 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
}
} catch (e) {
if (kDebugMode) {
print('SupplementsLog: Error duplicating supplement: $e');
printLog('Error duplicating supplement: $e');
}
}
}
@@ -307,16 +236,14 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
try {
await _databaseHelper.deleteSupplement(id);
// Cancel notifications
await _notificationService.cancelSupplementReminders(id);
await loadSupplements();
await _rescheduleAllNotifications();
// Trigger sync after deleting supplement
_triggerSyncIfEnabled();
} catch (e) {
if (kDebugMode) {
print('SupplementsLog: Error deleting supplement: $e');
printLog('Error deleting supplement: $e');
}
}
}
@@ -340,13 +267,13 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
// Show confirmation notification
final supplement = _supplements.firstWhere((s) => s.id == supplementId);
final unitsText = unitsTaken != null && unitsTaken != 1 ? '${unitsTaken.toStringAsFixed(unitsTaken % 1 == 0 ? 0 : 1)} ${supplement.unitType}' : '';
await _notificationService.showInstantNotification(
'Supplement Taken',
'Recorded ${supplement.name}${unitsText.isNotEmpty ? ' - $unitsText' : ''} (${supplement.ingredientsDisplay})',
await _notificationService.showInstant(
title: 'Supplement Taken',
body: 'Recorded ${supplement.name}${unitsText.isNotEmpty ? ' - $unitsText' : ''} (${supplement.ingredientsDisplay})',
);
} catch (e) {
if (kDebugMode) {
print('SupplementsLog: Error recording intake: $e');
printLog('Error recording intake: $e');
}
}
}
@@ -355,22 +282,22 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
try {
final today = DateTime.now();
if (kDebugMode) {
print('SupplementsLog: Loading intakes for date: ${today.year}-${today.month}-${today.day}');
printLog('Loading intakes for date: ${today.year}-${today.month}-${today.day}');
}
_todayIntakes = await _databaseHelper.getIntakesWithSupplementsForDate(today);
if (kDebugMode) {
print('SupplementsLog: Loaded ${_todayIntakes.length} intakes for today');
printLog('Loaded ${_todayIntakes.length} intakes for today');
for (var intake in _todayIntakes) {
print('SupplementsLog: - Supplement ID: ${intake['supplement_id']}, taken at: ${intake['takenAt']}');
printLog(' - Supplement ID: ${intake['supplement_id']}, taken at: ${intake['takenAt']}');
}
}
notifyListeners();
} catch (e) {
if (kDebugMode) {
print('SupplementsLog: Error loading today\'s intakes: $e');
printLog('Error loading today\'s intakes: $e');
}
}
}
@@ -381,7 +308,7 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
notifyListeners();
} catch (e) {
if (kDebugMode) {
print('SupplementsLog: Error loading monthly intakes: $e');
printLog('Error loading monthly intakes: $e');
}
}
}
@@ -391,7 +318,7 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
return await _databaseHelper.getIntakesWithSupplementsForDate(date);
} catch (e) {
if (kDebugMode) {
print('SupplementsLog: Error loading intakes for date: $e');
printLog('Error loading intakes for date: $e');
}
return [];
}
@@ -411,7 +338,7 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
_triggerSyncIfEnabled();
} catch (e) {
if (kDebugMode) {
print('SupplementsLog: Error deleting intake: $e');
printLog('Error deleting intake: $e');
}
}
}
@@ -430,7 +357,7 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
_triggerSyncIfEnabled();
} catch (e) {
if (kDebugMode) {
print('SupplementsLog: Error permanently deleting intake: $e');
printLog('Error permanently deleting intake: $e');
}
}
}
@@ -462,7 +389,7 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
// Method to manually refresh daily status (useful for testing or manual refresh)
Future<void> refreshDailyStatus() async {
if (kDebugMode) {
print('SupplementsLog: Manually refreshing daily status...');
printLog('Manually refreshing daily status...');
}
_lastDateCheck = DateTime.now();
await loadTodayIntakes();
@@ -475,20 +402,20 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
final lastCheckDate = DateTime(_lastDateCheck.year, _lastDateCheck.month, _lastDateCheck.day);
if (kDebugMode) {
print('SupplementsLog: Force checking date change...');
print('SupplementsLog: Current date: $currentDate');
print('SupplementsLog: Last check date: $lastCheckDate');
printLog('Force checking date change...');
printLog('Current date: $currentDate');
printLog('Last check date: $lastCheckDate');
}
if (currentDate != lastCheckDate) {
if (kDebugMode) {
print('SupplementsLog: Date change detected, refreshing intakes...');
printLog('Date change detected, refreshing intakes...');
}
_lastDateCheck = now;
await loadTodayIntakes();
} else {
if (kDebugMode) {
print('SupplementsLog: No date change detected');
printLog('No date change detected');
}
}
}
@@ -503,7 +430,7 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
notifyListeners();
} catch (e) {
if (kDebugMode) {
print('SupplementsLog: Error loading archived supplements: $e');
printLog('Error loading archived supplements: $e');
}
}
}
@@ -518,7 +445,7 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
_triggerSyncIfEnabled();
} catch (e) {
if (kDebugMode) {
print('SupplementsLog: Error archiving supplement: $e');
printLog('Error archiving supplement: $e');
}
}
}
@@ -533,7 +460,7 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
_triggerSyncIfEnabled();
} catch (e) {
if (kDebugMode) {
print('SupplementsLog: Error unarchiving supplement: $e');
printLog('Error unarchiving supplement: $e');
}
}
}
@@ -547,32 +474,39 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
_triggerSyncIfEnabled();
} catch (e) {
if (kDebugMode) {
print('SupplementsLog: Error permanently deleting archived supplement: $e');
printLog('Error permanently deleting archived supplement: $e');
}
}
}
// Debug methods for notification testing
Future<void> testNotifications() async {
await _notificationService.testNotification();
await _notificationService.showInstant(
title: 'Test Notification',
body: 'This is a test notification to verify the system is working.',
);
}
Future<void> testScheduledNotification() async {
await _notificationService.testScheduledNotification();
await _notificationService.showInstant(
title: 'Test Scheduled Notification',
body: 'This is a simple test notification.',
);
}
Future<void> testNotificationActions() async {
await _notificationService.testNotificationWithActions();
await _notificationService.showInstant(
title: 'Test Action Notification',
body: 'Actions are not available in the simple notification service.',
);
}
Future<List<PendingNotificationRequest>> getPendingNotifications() async {
return await _notificationService.getPendingNotifications();
// Not supported in simple service; return empty list for compatibility.
return [];
}
// Get pending notifications with retry information from database
Future<List<Map<String, dynamic>>> getTrackedNotifications() async {
return await DatabaseHelper.instance.getPendingNotifications();
}
// Debug method to test notification persistence
Future<void> rescheduleAllNotifications() async {
@@ -581,6 +515,6 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
// Debug method to cancel all notifications
Future<void> cancelAllNotifications() async {
await _notificationService.cancelAllReminders();
await _notificationService.cancelAll();
}
}