6 Commits

11 changed files with 1566 additions and 469 deletions

View File

@@ -31,8 +31,11 @@ class MyApp extends StatelessWidget {
child: Consumer2<SettingsProvider, SimpleSyncProvider>(
builder: (context, settingsProvider, syncProvider, child) {
// Set up the sync completion callback to refresh supplement data
// and initialize auto-sync integration
WidgetsBinding.instance.addPostFrameCallback((_) {
final supplementProvider = context.read<SupplementProvider>();
// Set up sync completion callback
syncProvider.setOnSyncCompleteCallback(() async {
if (kDebugMode) {
print('SupplementsLog: Sync completed, refreshing UI data...');
@@ -43,6 +46,14 @@ class MyApp extends StatelessWidget {
print('SupplementsLog: UI data refreshed after sync');
}
});
// Initialize auto-sync service
syncProvider.initializeAutoSync(settingsProvider);
// Set up auto-sync callback for data changes
supplementProvider.setOnDataChangedCallback(() {
syncProvider.triggerAutoSyncIfEnabled();
});
});
return MaterialApp(

View File

@@ -9,7 +9,7 @@ enum ThemeOption {
class SettingsProvider extends ChangeNotifier {
ThemeOption _themeOption = ThemeOption.system;
// Time range settings (stored as hours, 0-23)
int _morningStart = 5;
int _morningEnd = 10;
@@ -19,14 +19,18 @@ class SettingsProvider extends ChangeNotifier {
int _eveningEnd = 22;
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;
int _autoSyncDebounceSeconds = 5;
ThemeOption get themeOption => _themeOption;
// Time range getters
int get morningStart => _morningStart;
int get morningEnd => _morningEnd;
@@ -36,22 +40,26 @@ class SettingsProvider extends ChangeNotifier {
int get eveningEnd => _eveningEnd;
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;
int get autoSyncDebounceSeconds => _autoSyncDebounceSeconds;
// Helper method to get formatted time ranges for display
String get morningRange => '${_formatHour(_morningStart)} - ${_formatHour((_morningEnd + 1) % 24)}';
String get afternoonRange => '${_formatHour(_afternoonStart)} - ${_formatHour((_afternoonEnd + 1) % 24)}';
String get eveningRange => '${_formatHour(_eveningStart)} - ${_formatHour((_eveningEnd + 1) % 24)}';
String get nightRange => '${_formatHour(_nightStart)} - ${_formatHour((_nightEnd + 1) % 24)}';
String _formatHour(int hour) {
return '${hour.toString().padLeft(2, '0')}:00';
}
ThemeMode get themeMode {
switch (_themeOption) {
case ThemeOption.light:
@@ -67,7 +75,7 @@ class SettingsProvider extends ChangeNotifier {
final prefs = await SharedPreferences.getInstance();
final themeIndex = prefs.getInt('theme_option') ?? 0;
_themeOption = ThemeOption.values[themeIndex];
// Load time range settings
_morningStart = prefs.getInt('morning_start') ?? 5;
_morningEnd = prefs.getInt('morning_end') ?? 10;
@@ -77,19 +85,23 @@ class SettingsProvider extends ChangeNotifier {
_eveningEnd = prefs.getInt('evening_end') ?? 22;
_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;
_autoSyncDebounceSeconds = prefs.getInt('auto_sync_debounce_seconds') ?? 30;
notifyListeners();
}
Future<void> setThemeOption(ThemeOption option) async {
_themeOption = option;
notifyListeners();
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('theme_option', option.index);
}
@@ -146,14 +158,14 @@ class SettingsProvider extends ChangeNotifier {
if (morningStart > morningEnd) return false;
if (afternoonStart > afternoonEnd) return false;
if (eveningStart > eveningEnd) return false;
// Night can wrap around midnight, so we allow nightStart > nightEnd
// Check for overlaps in sequential periods
if (morningEnd >= afternoonStart) return false;
if (afternoonEnd >= eveningStart) return false;
if (eveningEnd >= nightStart) return false;
return true;
}
@@ -174,7 +186,7 @@ class SettingsProvider extends ChangeNotifier {
int afternoonCount = 0;
int eveningCount = 0;
int nightCount = 0;
for (final hour in hours) {
if (hour >= _morningStart && hour <= _morningEnd) {
morningCount++;
@@ -186,13 +198,13 @@ class SettingsProvider extends ChangeNotifier {
nightCount++;
}
}
// If supplement is taken throughout the day (has times in multiple periods)
final periodsCount = (morningCount > 0 ? 1 : 0) +
(afternoonCount > 0 ? 1 : 0) +
(eveningCount > 0 ? 1 : 0) +
final periodsCount = (morningCount > 0 ? 1 : 0) +
(afternoonCount > 0 ? 1 : 0) +
(eveningCount > 0 ? 1 : 0) +
(nightCount > 0 ? 1 : 0);
if (periodsCount >= 2) {
// Categorize based on the earliest reminder time for consistency
final earliestHour = hours.reduce((a, b) => a < b ? a : b);
@@ -206,7 +218,7 @@ class SettingsProvider extends ChangeNotifier {
return 'night';
}
}
// If all times are in one period, categorize accordingly
if (morningCount > 0) {
return 'morning';
@@ -236,7 +248,7 @@ class SettingsProvider extends ChangeNotifier {
Future<void> setPersistentReminders(bool enabled) async {
_persistentReminders = enabled;
notifyListeners();
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('persistent_reminders', enabled);
}
@@ -244,7 +256,7 @@ class SettingsProvider extends ChangeNotifier {
Future<void> setReminderRetryInterval(int minutes) async {
_reminderRetryInterval = minutes;
notifyListeners();
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('reminder_retry_interval', minutes);
}
@@ -252,8 +264,25 @@ class SettingsProvider extends ChangeNotifier {
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 {
_autoSyncEnabled = enabled;
notifyListeners();
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('auto_sync_enabled', enabled);
}
Future<void> setAutoSyncDebounceSeconds(int seconds) async {
_autoSyncDebounceSeconds = seconds;
notifyListeners();
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('auto_sync_debounce_seconds', seconds);
}
}

View File

@@ -1,7 +1,8 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../services/database_sync_service.dart';
import '../services/auto_sync_service.dart';
import 'settings_provider.dart';
class SimpleSyncProvider with ChangeNotifier {
final DatabaseSyncService _syncService = DatabaseSyncService();
@@ -9,6 +10,12 @@ class SimpleSyncProvider with ChangeNotifier {
// Callback for UI refresh after sync
VoidCallback? _onSyncCompleteCallback;
// Auto-sync service
AutoSyncService? _autoSyncService;
// Track if current sync is auto-triggered
bool _isAutoSync = false;
// Getters
SyncStatus get status => _syncService.status;
String? get lastError => _syncService.lastError;
@@ -17,6 +24,14 @@ class SimpleSyncProvider with ChangeNotifier {
bool get isSyncing => status == SyncStatus.downloading ||
status == SyncStatus.merging ||
status == SyncStatus.uploading;
bool get isAutoSync => _isAutoSync;
AutoSyncService? get autoSyncService => _autoSyncService;
// Auto-sync error handling getters
bool get isAutoSyncDisabledDueToErrors => _autoSyncService?.isAutoDisabledDueToErrors ?? false;
int get autoSyncConsecutiveFailures => _autoSyncService?.consecutiveFailures ?? 0;
String? get autoSyncLastError => _autoSyncService?.lastErrorMessage;
bool get hasAutoSyncScheduledRetry => _autoSyncService?.hasScheduledRetry ?? false;
// Configuration getters
String? get serverUrl => _syncService.serverUrl;
@@ -43,6 +58,23 @@ class SimpleSyncProvider with ChangeNotifier {
_onSyncCompleteCallback = callback;
}
/// Initialize auto-sync service with settings provider
void initializeAutoSync(SettingsProvider settingsProvider) {
_autoSyncService = AutoSyncService(
syncProvider: this,
settingsProvider: settingsProvider,
);
if (kDebugMode) {
print('SimpleSyncProvider: Auto-sync service initialized');
}
}
/// Triggers auto-sync if enabled and configured
void triggerAutoSyncIfEnabled() {
_autoSyncService?.triggerAutoSync();
}
Future<void> _loadConfiguration() async {
await _syncService.loadSavedConfiguration();
notifyListeners(); // Notify UI that configuration might be available
@@ -67,11 +99,14 @@ class SimpleSyncProvider with ChangeNotifier {
return await _syncService.testConnection();
}
Future<void> syncDatabase() async {
Future<void> syncDatabase({bool isAutoSync = false}) async {
if (!isConfigured) {
throw Exception('Sync not configured');
}
_isAutoSync = isAutoSync;
notifyListeners();
try {
await _syncService.syncDatabase();
} catch (e) {
@@ -79,6 +114,9 @@ class SimpleSyncProvider with ChangeNotifier {
print('SupplementsLog: Sync failed in provider: $e');
}
rethrow;
} finally {
_isAutoSync = false;
notifyListeners();
}
}
@@ -87,20 +125,46 @@ class SimpleSyncProvider with ChangeNotifier {
notifyListeners();
}
/// Resets auto-sync error state and re-enables auto-sync if it was disabled
void resetAutoSyncErrors() {
_autoSyncService?.resetErrorState();
notifyListeners();
}
String getStatusText() {
final syncType = _isAutoSync ? 'Auto-sync' : 'Sync';
// Check for auto-sync specific errors first
if (isAutoSyncDisabledDueToErrors) {
return 'Auto-sync disabled due to repeated failures. ${autoSyncLastError ?? 'Check sync settings.'}';
}
switch (status) {
case SyncStatus.idle:
if (hasAutoSyncScheduledRetry) {
return 'Auto-sync will retry shortly...';
}
return 'Ready to sync';
case SyncStatus.downloading:
return 'Downloading remote database...';
return '$syncType: Downloading remote database...';
case SyncStatus.merging:
return 'Merging databases...';
return '$syncType: Merging databases...';
case SyncStatus.uploading:
return 'Uploading database...';
return '$syncType: Uploading database...';
case SyncStatus.completed:
return 'Sync completed successfully';
return '$syncType completed successfully';
case SyncStatus.error:
return 'Sync failed: ${lastError ?? 'Unknown error'}';
// For auto-sync errors, show more specific messages
if (_isAutoSync && autoSyncLastError != null) {
return 'Auto-sync failed: $autoSyncLastError';
}
return '$syncType failed: ${lastError ?? 'Unknown error'}';
}
}
@override
void dispose() {
_autoSyncService?.dispose();
super.dispose();
}
}

View File

@@ -224,6 +224,13 @@ class _AddSupplementScreenState extends State<AddSupplementScreen> {
appBar: AppBar(
title: Text(isEditing ? 'Edit Supplement' : 'Add Supplement'),
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
actions: [
IconButton(
tooltip: isEditing ? 'Update Supplement' : 'Save Supplement',
onPressed: _saveSupplement,
icon: const Icon(Icons.save),
),
],
),
body: Form(
key: _formKey,
@@ -482,17 +489,7 @@ class _AddSupplementScreenState extends State<AddSupplementScreen> {
),
const SizedBox(height: 24),
// Save button
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: _saveSupplement,
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(16),
),
child: Text(isEditing ? 'Update Supplement' : 'Add Supplement'),
),
),
// Save is now in the AppBar for consistency with app-wide pattern
],
),
),
@@ -560,21 +557,24 @@ class _AddSupplementScreenState extends State<AddSupplementScreen> {
void _saveSupplement() async {
if (_formKey.currentState!.validate()) {
// Validate that we have at least one ingredient with name and amount
final validIngredients = _ingredientControllers.where((controller) =>
controller.nameController.text.trim().isNotEmpty &&
(double.tryParse(controller.amountController.text) ?? 0) > 0
).map((controller) => Ingredient(
name: controller.nameController.text.trim(),
amount: double.tryParse(controller.amountController.text) ?? 0.0,
unit: controller.selectedUnit,
syncId: const Uuid().v4(),
lastModified: DateTime.now(),
)).toList();
final validIngredients = _ingredientControllers
.where((controller) =>
controller.nameController.text.trim().isNotEmpty &&
(double.tryParse(controller.amountController.text) ?? 0) > 0)
.map((controller) => Ingredient(
name: controller.nameController.text.trim(),
amount: double.tryParse(controller.amountController.text) ?? 0.0,
unit: controller.selectedUnit,
syncId: const Uuid().v4(),
lastModified: DateTime.now(),
))
.toList();
if (validIngredients.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Please add at least one ingredient with name and amount'),
content:
Text('Please add at least one ingredient with name and amount'),
),
);
return;
@@ -583,14 +583,20 @@ class _AddSupplementScreenState extends State<AddSupplementScreen> {
final supplement = Supplement(
id: widget.supplement?.id,
name: _nameController.text.trim(),
brand: _brandController.text.trim().isNotEmpty ? _brandController.text.trim() : null,
brand: _brandController.text.trim().isNotEmpty
? _brandController.text.trim()
: null,
ingredients: validIngredients,
numberOfUnits: int.parse(_numberOfUnitsController.text),
unitType: _selectedUnitType,
frequencyPerDay: _frequencyPerDay,
reminderTimes: _reminderTimes,
notes: _notesController.text.trim().isNotEmpty ? _notesController.text.trim() : null,
notes: _notesController.text.trim().isNotEmpty
? _notesController.text.trim()
: null,
createdAt: widget.supplement?.createdAt ?? DateTime.now(),
syncId: widget.supplement?.syncId, // Preserve syncId on update
lastModified: DateTime.now(), // Always update lastModified on save
);
final provider = context.read<SupplementProvider>();

View File

@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import '../providers/settings_provider.dart';
import '../providers/supplement_provider.dart';
class HistoryScreen extends StatefulWidget {
@@ -125,27 +126,33 @@ class _HistoryScreenState extends State<HistoryScreen> {
Expanded(
flex: 3,
child: Container(
margin: const EdgeInsets.fromLTRB(0, 16, 16, 16),
child: _buildSelectedDayDetails(groupedIntakes),
// add a bit more horizontal spacing between calendar and card
margin: const EdgeInsets.fromLTRB(8, 16, 16, 16),
child: SingleChildScrollView(
child: _buildSelectedDayDetails(groupedIntakes),
),
),
),
],
);
} else {
// Mobile layout: vertical stack
return Column(
children: [
// Calendar
Container(
margin: const EdgeInsets.symmetric(horizontal: 16),
child: _buildCalendar(groupedIntakes),
),
const SizedBox(height: 16),
// Selected day details
Expanded(
child: _buildSelectedDayDetails(groupedIntakes),
),
],
return SingleChildScrollView(
child: Column(
children: [
// Calendar
Container(
margin: const EdgeInsets.symmetric(horizontal: 16),
child: _buildCalendar(groupedIntakes),
),
const SizedBox(height: 16),
// Selected day details
Container(
margin: const EdgeInsets.symmetric(horizontal: 16),
child: _buildSelectedDayDetails(groupedIntakes),
),
],
),
);
}
},
@@ -479,78 +486,208 @@ class _HistoryScreenState extends State<HistoryScreen> {
],
),
),
Expanded(
child: ListView.builder(
padding: EdgeInsets.all(isWideScreen ? 20 : 16),
itemCount: dayIntakes.length,
itemBuilder: (context, index) {
final intake = dayIntakes[index];
final takenAt = DateTime.parse(intake['takenAt']);
final units = (intake['unitsTaken'] as num?)?.toDouble() ?? 1.0;
return Card(
margin: const EdgeInsets.only(bottom: 12),
elevation: 2,
child: Padding(
padding: EdgeInsets.all(isWideScreen ? 16 : 12),
Padding(
padding: EdgeInsets.all(isWideScreen ? 20 : 16),
child: Builder(
builder: (context) {
final settingsProvider = Provider.of<SettingsProvider>(context, listen: false);
// Sort once per render
final sortedDayIntakes = List<Map<String, dynamic>>.from(dayIntakes)
..sort((a, b) => DateTime.parse(a['takenAt']).compareTo(DateTime.parse(b['takenAt'])));
// Helpers
String timeCategory(DateTime dt) {
final h = dt.hour;
if (h >= settingsProvider.morningStart && h <= settingsProvider.morningEnd) return 'morning';
if (h >= settingsProvider.afternoonStart && h <= settingsProvider.afternoonEnd) return 'afternoon';
if (h >= settingsProvider.eveningStart && h <= settingsProvider.eveningEnd) return 'evening';
final ns = settingsProvider.nightStart;
final ne = settingsProvider.nightEnd;
final inNight = ns <= ne ? (h >= ns && h <= ne) : (h >= ns || h <= ne);
return inNight ? 'night' : 'anytime';
}
String? sectionRange(String cat) {
switch (cat) {
case 'morning':
return settingsProvider.morningRange;
case 'afternoon':
return settingsProvider.afternoonRange;
case 'evening':
return settingsProvider.eveningRange;
case 'night':
return settingsProvider.nightRange;
default:
return null;
}
}
Widget headerFor(String cat) {
late final IconData icon;
late final Color color;
late final String title;
switch (cat) {
case 'morning':
icon = Icons.wb_sunny;
color = Colors.orange;
title = 'Morning';
break;
case 'afternoon':
icon = Icons.light_mode;
color = Colors.blue;
title = 'Afternoon';
break;
case 'evening':
icon = Icons.nightlight_round;
color = Colors.indigo;
title = 'Evening';
break;
case 'night':
icon = Icons.bedtime;
color = Colors.purple;
title = 'Night';
break;
default:
icon = Icons.schedule;
color = Colors.grey;
title = 'Anytime';
}
final range = sectionRange(cat);
return Container(
margin: const EdgeInsets.only(bottom: 12),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
decoration: BoxDecoration(
color: color.withOpacity(0.1),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: color.withOpacity(0.3),
width: 1,
),
),
child: Row(
children: [
CircleAvatar(
backgroundColor: Theme.of(context).colorScheme.primary,
radius: isWideScreen ? 24 : 20,
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: color.withOpacity(0.2),
shape: BoxShape.circle,
),
child: Icon(
Icons.medication,
color: Theme.of(context).colorScheme.onPrimary,
size: isWideScreen ? 24 : 20,
icon,
size: 20,
color: color,
),
),
SizedBox(width: isWideScreen ? 16 : 12),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
intake['supplementName'],
title,
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: isWideScreen ? 16 : 14,
fontSize: 18,
fontWeight: FontWeight.bold,
color: color,
),
),
const SizedBox(height: 4),
Text(
'${units.toStringAsFixed(units % 1 == 0 ? 0 : 1)} ${intake['supplementUnitType'] ?? 'units'} at ${DateFormat('HH:mm').format(takenAt)}',
style: TextStyle(
color: Theme.of(context).colorScheme.primary,
fontWeight: FontWeight.w500,
fontSize: isWideScreen ? 14 : 12,
),
),
if (intake['notes'] != null && intake['notes'].toString().isNotEmpty) ...[
const SizedBox(height: 4),
if (range != null) ...[
Text(
intake['notes'],
'($range)',
style: TextStyle(
fontSize: isWideScreen ? 13 : 12,
fontStyle: FontStyle.italic,
color: Theme.of(context).colorScheme.onSurfaceVariant,
fontSize: 12,
fontWeight: FontWeight.w500,
color: color.withOpacity(0.8),
),
),
],
],
),
),
IconButton(
icon: Icon(
Icons.delete_outline,
color: Colors.red.shade400,
size: isWideScreen ? 24 : 20,
),
onPressed: () => _deleteIntake(context, intake['id'], intake['supplementName']),
tooltip: 'Delete intake',
),
],
),
),
);
}
// Build a non-scrollable list so the card auto-expands to fit content
final List<Widget> children = [];
for (int index = 0; index < sortedDayIntakes.length; index++) {
final intake = sortedDayIntakes[index];
final takenAt = DateTime.parse(intake['takenAt']);
final units = (intake['unitsTaken'] as num?)?.toDouble() ?? 1.0;
final currentCategory = timeCategory(takenAt);
final needsHeader = index == 0
? true
: currentCategory != timeCategory(DateTime.parse(sortedDayIntakes[index - 1]['takenAt']));
if (needsHeader) {
children.add(headerFor(currentCategory));
}
children.add(
Card(
margin: const EdgeInsets.only(bottom: 12),
elevation: 2,
child: Padding(
padding: EdgeInsets.all(isWideScreen ? 16 : 12),
child: Row(
children: [
CircleAvatar(
backgroundColor: Theme.of(context).colorScheme.primary,
radius: isWideScreen ? 24 : 20,
child: Icon(
Icons.medication,
color: Theme.of(context).colorScheme.onPrimary,
size: isWideScreen ? 24 : 20,
),
),
SizedBox(width: isWideScreen ? 16 : 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
intake['supplementName'],
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: isWideScreen ? 16 : 14,
),
),
const SizedBox(height: 4),
Text(
'${units.toStringAsFixed(units % 1 == 0 ? 0 : 1)} ${intake['supplementUnitType'] ?? 'units'} at ${DateFormat('HH:mm').format(takenAt)}',
style: TextStyle(
color: Theme.of(context).colorScheme.primary,
fontWeight: FontWeight.w500,
fontSize: isWideScreen ? 14 : 12,
),
),
if (intake['notes'] != null && intake['notes'].toString().isNotEmpty) ...[
const SizedBox(height: 4),
Text(
intake['notes'],
style: TextStyle(
fontSize: isWideScreen ? 13 : 12,
fontStyle: FontStyle.italic,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
],
],
),
),
IconButton(
icon: Icon(
Icons.delete_outline,
color: Colors.red.shade400,
size: isWideScreen ? 24 : 20,
),
onPressed: () => _deleteIntake(context, intake['id'], intake['supplementName']),
tooltip: 'Delete intake',
),
],
),
),
),
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: children,
);
},
),

View File

@@ -1,8 +1,9 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../services/database_sync_service.dart';
import '../providers/settings_provider.dart';
import '../providers/simple_sync_provider.dart';
import '../services/database_sync_service.dart';
class SimpleSyncSettingsScreen extends StatefulWidget {
const SimpleSyncSettingsScreen({super.key});
@@ -17,7 +18,7 @@ class _SimpleSyncSettingsScreenState extends State<SimpleSyncSettingsScreen> {
final _usernameController = TextEditingController();
final _passwordController = TextEditingController();
final _remotePathController = TextEditingController();
String _previewUrl = '';
@override
@@ -27,11 +28,11 @@ class _SimpleSyncSettingsScreenState extends State<SimpleSyncSettingsScreen> {
_usernameController.addListener(_updatePreviewUrl);
_loadSavedConfiguration();
}
void _loadSavedConfiguration() {
WidgetsBinding.instance.addPostFrameCallback((_) {
final syncProvider = context.read<SimpleSyncProvider>();
if (syncProvider.serverUrl != null) {
_serverUrlController.text = _extractHostnameFromUrl(syncProvider.serverUrl!);
}
@@ -44,11 +45,11 @@ class _SimpleSyncSettingsScreenState extends State<SimpleSyncSettingsScreen> {
if (syncProvider.remotePath != null) {
_remotePathController.text = syncProvider.remotePath!;
}
_updatePreviewUrl();
});
}
String _extractHostnameFromUrl(String fullUrl) {
try {
final uri = Uri.parse(fullUrl);
@@ -81,30 +82,35 @@ class _SimpleSyncSettingsScreenState extends State<SimpleSyncSettingsScreen> {
@override
Widget build(BuildContext context) {
final syncProvider = context.watch<SimpleSyncProvider>();
return Scaffold(
appBar: AppBar(
title: const Text('Database Sync Settings'),
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
actions: [
IconButton(
tooltip: 'Save Configuration',
onPressed: syncProvider.isSyncing ? null : _configureSync,
icon: const Icon(Icons.save),
),
],
),
body: Consumer<SimpleSyncProvider>(
builder: (context, syncProvider, child) {
return SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildStatusCard(syncProvider),
const SizedBox(height: 20),
_buildConfigurationSection(),
const SizedBox(height: 20),
_buildActionButtons(syncProvider),
],
),
),
);
},
body: SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildStatusCard(syncProvider),
const SizedBox(height: 20),
_buildConfigurationSection(syncProvider),
const SizedBox(height: 20),
_buildActionButtons(),
],
),
),
),
);
}
@@ -116,17 +122,17 @@ class _SimpleSyncSettingsScreenState extends State<SimpleSyncSettingsScreen> {
switch (syncProvider.status) {
case SyncStatus.idle:
icon = Icons.sync;
icon = syncProvider.isAutoSync ? Icons.sync_alt : Icons.sync;
color = Colors.blue;
break;
case SyncStatus.downloading:
case SyncStatus.merging:
case SyncStatus.uploading:
icon = Icons.sync;
color = Colors.orange;
icon = syncProvider.isAutoSync ? Icons.sync_alt : Icons.sync;
color = syncProvider.isAutoSync ? Colors.deepOrange : Colors.orange;
break;
case SyncStatus.completed:
icon = Icons.check_circle;
icon = syncProvider.isAutoSync ? Icons.check_circle_outline : Icons.check_circle;
color = Colors.green;
break;
case SyncStatus.error:
@@ -152,8 +158,28 @@ class _SimpleSyncSettingsScreenState extends State<SimpleSyncSettingsScreen> {
),
),
),
// Sync action inside the status card
if (syncProvider.isSyncing) ...[
const SizedBox(width: 12),
SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2.2,
valueColor: AlwaysStoppedAnimation<Color>(color),
),
),
] else ...[
IconButton(
tooltip: 'Sync Database',
onPressed: (!syncProvider.isConfigured || syncProvider.isSyncing) ? null : _syncDatabase,
icon: const Icon(Icons.sync),
color: Theme.of(context).colorScheme.primary,
),
],
],
),
_buildAutoSyncStatusIndicator(syncProvider),
if (syncProvider.lastSyncTime != null) ...[
const SizedBox(height: 8),
Text(
@@ -161,19 +187,73 @@ class _SimpleSyncSettingsScreenState extends State<SimpleSyncSettingsScreen> {
style: Theme.of(context).textTheme.bodySmall,
),
],
if (syncProvider.lastError != null) ...[
// Show auto-sync specific errors
if (syncProvider.isAutoSyncDisabledDueToErrors) ...[
const SizedBox(height: 8),
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.red.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.red.withValues(alpha: 0.3)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.warning, color: Colors.red, size: 20),
const SizedBox(width: 8),
Expanded(
child: Text(
'Auto-sync disabled due to repeated failures',
style: Theme.of(context).textTheme.titleSmall?.copyWith(
color: Colors.red,
fontWeight: FontWeight.w600,
),
),
),
],
),
if (syncProvider.autoSyncLastError != null) ...[
const SizedBox(height: 8),
Text(
syncProvider.autoSyncLastError!,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Colors.red[700],
),
),
],
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton.icon(
onPressed: () => syncProvider.resetAutoSyncErrors(),
icon: const Icon(Icons.refresh, size: 16),
label: const Text('Reset & Re-enable'),
style: TextButton.styleFrom(
foregroundColor: Colors.red,
),
),
],
),
],
),
),
] else if (syncProvider.lastError != null) ...[
const SizedBox(height: 8),
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.red.withOpacity(0.1),
color: Colors.red.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(4),
),
child: Row(
children: [
Expanded(
child: Text(
syncProvider.lastError!,
_getErrorMessage(syncProvider),
style: const TextStyle(color: Colors.red),
),
),
@@ -191,141 +271,260 @@ class _SimpleSyncSettingsScreenState extends State<SimpleSyncSettingsScreen> {
);
}
Widget _buildConfigurationSection() {
return Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'WebDAV Configuration',
style: Theme.of(context).textTheme.titleLarge,
Widget _buildConfigurationSection(SimpleSyncProvider syncProvider) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Card(
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Sync Configuration',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
_buildAutoSyncSection(),
],
),
const SizedBox(height: 16),
TextFormField(
controller: _serverUrlController,
decoration: const InputDecoration(
labelText: 'Server URL',
hintText: 'your-nextcloud.com',
helperText: 'Enter just the hostname. We\'ll auto-detect the full WebDAV path.',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 12),
Card(
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'WebDAV Settings',
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 8),
TextFormField(
controller: _serverUrlController,
decoration: const InputDecoration(
labelText: 'Server URL',
hintText: 'your-nextcloud.com',
helperText: 'Enter just the hostname. We\'ll auto-detect the full WebDAV path.',
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a server URL';
}
return null;
},
),
const SizedBox(height: 8),
TextFormField(
controller: _usernameController,
decoration: const InputDecoration(
labelText: 'Username',
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a username';
}
return null;
},
),
if (_previewUrl.isNotEmpty) ...[
const SizedBox(height: 6),
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerHighest.withValues(alpha: 0.3),
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: Theme.of(context).colorScheme.outline.withValues(alpha: 0.5),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'WebDAV URL Preview:',
style: Theme.of(context).textTheme.labelMedium,
),
const SizedBox(height: 4),
SelectableText(
_previewUrl,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
fontFamily: 'monospace',
color: Theme.of(context).colorScheme.primary,
),
),
const SizedBox(height: 6),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ElevatedButton.icon(
onPressed: syncProvider.isSyncing ? null : _testConnection,
icon: const Icon(Icons.link),
label: const Text('Test'),
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
elevation: 0,
),
),
],
),
],
),
),
],
const SizedBox(height: 8),
TextFormField(
controller: _passwordController,
decoration: const InputDecoration(
labelText: 'Password',
border: OutlineInputBorder(),
),
obscureText: true,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a password';
}
return null;
},
),
const SizedBox(height: 8),
TextFormField(
controller: _remotePathController,
decoration: const InputDecoration(
labelText: 'Remote Path (optional)',
hintText: 'Supplements/',
border: OutlineInputBorder(),
),
),
],
),
),
),
],
);
}
Widget _buildActionButtons() {
// Buttons have been moved into the AppBar / cards. Keep a small spacer here for layout.
return const SizedBox.shrink();
}
Widget _buildAutoSyncSection() {
return Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
return Consumer<SimpleSyncProvider>(
builder: (context, syncProvider, child) {
return Container(
padding: const EdgeInsets.all(16.0),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerHighest.withValues(alpha: 0.3),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: Theme.of(context).colorScheme.outline.withValues(alpha: 0.5),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SwitchListTile(
title: Row(
children: [
const Text(
'Auto-sync',
style: TextStyle(fontWeight: FontWeight.w600),
),
const SizedBox(width: 8),
_buildAutoSyncStatusBadge(settingsProvider, syncProvider),
],
),
subtitle: Text(
settingsProvider.autoSyncEnabled
? 'Automatically sync when you make changes'
: 'Sync manually using the sync button',
style: Theme.of(context).textTheme.bodySmall,
),
value: settingsProvider.autoSyncEnabled,
onChanged: (bool value) async {
await settingsProvider.setAutoSyncEnabled(value);
},
contentPadding: EdgeInsets.zero,
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a server URL';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _usernameController,
decoration: const InputDecoration(
labelText: 'Username',
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a username';
}
return null;
},
),
if (_previewUrl.isNotEmpty) ...[
const SizedBox(height: 8),
if (settingsProvider.autoSyncEnabled) ...[
const SizedBox(height: 8),
Padding(
padding: const EdgeInsets.only(left: 16.0),
child: Text(
'Changes are debounced for ${settingsProvider.autoSyncDebounceSeconds} seconds to prevent excessive syncing.',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
fontStyle: FontStyle.italic,
),
),
),
const SizedBox(height: 12),
Padding(
padding: const EdgeInsets.only(left: 16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Debounce timeout',
style: Theme.of(context).textTheme.titleSmall,
),
const SizedBox(height: 8),
SegmentedButton<int>(
segments: const [
ButtonSegment(value: 1, label: Text('1s')),
ButtonSegment(value: 5, label: Text('5s')),
ButtonSegment(value: 15, label: Text('15s')),
ButtonSegment(value: 30, label: Text('30s')),
],
selected: {settingsProvider.autoSyncDebounceSeconds},
onSelectionChanged: (values) {
settingsProvider.setAutoSyncDebounceSeconds(values.first);
},
),
],
),
),
],
const SizedBox(height: 12),
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerHighest.withOpacity(0.3),
color: Theme.of(context).colorScheme.primaryContainer.withValues(alpha: 0.3),
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: Theme.of(context).colorScheme.outline.withOpacity(0.5),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
child: Row(
children: [
Text(
'WebDAV URL Preview:',
style: Theme.of(context).textTheme.labelMedium,
Icon(
Icons.info_outline,
size: 16,
color: Theme.of(context).colorScheme.primary,
),
const SizedBox(height: 4),
SelectableText(
_previewUrl,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
fontFamily: 'monospace',
color: Theme.of(context).colorScheme.primary,
const SizedBox(width: 8),
Expanded(
child: Text(
'Auto-sync triggers when you add, update, or delete supplements and intakes. Configure your WebDAV settings below to enable syncing.',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onPrimaryContainer,
),
),
),
],
),
),
],
const SizedBox(height: 16),
TextFormField(
controller: _passwordController,
decoration: const InputDecoration(
labelText: 'Password',
border: OutlineInputBorder(),
),
obscureText: true,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a password';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _remotePathController,
decoration: const InputDecoration(
labelText: 'Remote Path (optional)',
hintText: 'Supplements/',
border: OutlineInputBorder(),
),
),
],
),
),
);
}
Widget _buildActionButtons(SimpleSyncProvider syncProvider) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ElevatedButton(
onPressed: syncProvider.isSyncing ? null : _testConnection,
child: const Text('Test Connection'),
),
const SizedBox(height: 12),
ElevatedButton(
onPressed: syncProvider.isSyncing ? null : _configureSync,
child: const Text('Save Configuration'),
),
const SizedBox(height: 12),
ElevatedButton(
onPressed: (!syncProvider.isConfigured || syncProvider.isSyncing)
? null
: _syncDatabase,
style: ElevatedButton.styleFrom(
backgroundColor: Theme.of(context).primaryColor,
foregroundColor: Colors.white,
),
child: syncProvider.isSyncing
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
),
)
: const Text('Sync Database'),
),
],
);
},
);
},
);
}
@@ -333,31 +532,31 @@ class _SimpleSyncSettingsScreenState extends State<SimpleSyncSettingsScreen> {
if (!_formKey.currentState!.validate()) return;
final syncProvider = context.read<SimpleSyncProvider>();
try {
// Construct the full WebDAV URL from the simple hostname
final fullWebDAVUrl = _constructWebDAVUrl(
_serverUrlController.text.trim(),
_usernameController.text.trim(),
);
// Configure temporarily for testing
await syncProvider.configure(
serverUrl: fullWebDAVUrl,
username: _usernameController.text.trim(),
password: _passwordController.text.trim(),
remotePath: _remotePathController.text.trim().isEmpty
? 'Supplements'
remotePath: _remotePathController.text.trim().isEmpty
? 'Supplements'
: _remotePathController.text.trim(),
);
final success = await syncProvider.testConnection();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(success
? 'Connection successful!'
content: Text(success
? 'Connection successful!'
: 'Connection failed. Check your settings.'),
backgroundColor: success ? Colors.green : Colors.red,
),
@@ -379,20 +578,20 @@ class _SimpleSyncSettingsScreenState extends State<SimpleSyncSettingsScreen> {
if (!_formKey.currentState!.validate()) return;
final syncProvider = context.read<SimpleSyncProvider>();
try {
// Construct the full WebDAV URL from the simple hostname
final fullWebDAVUrl = _constructWebDAVUrl(
_serverUrlController.text.trim(),
_usernameController.text.trim(),
);
await syncProvider.configure(
serverUrl: fullWebDAVUrl,
username: _usernameController.text.trim(),
password: _passwordController.text.trim(),
remotePath: _remotePathController.text.trim().isEmpty
? 'Supplements'
remotePath: _remotePathController.text.trim().isEmpty
? 'Supplements'
: _remotePathController.text.trim(),
);
@@ -418,14 +617,14 @@ class _SimpleSyncSettingsScreenState extends State<SimpleSyncSettingsScreen> {
Future<void> _syncDatabase() async {
final syncProvider = context.read<SimpleSyncProvider>();
try {
await syncProvider.syncDatabase();
await syncProvider.syncDatabase(isAutoSync: false);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Database sync completed!'),
content: Text('Manual sync completed!'),
backgroundColor: Colors.green,
),
);
@@ -434,7 +633,7 @@ class _SimpleSyncSettingsScreenState extends State<SimpleSyncSettingsScreen> {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Sync failed: $e'),
content: Text('Manual sync failed: $e'),
backgroundColor: Colors.red,
),
);
@@ -450,17 +649,200 @@ class _SimpleSyncSettingsScreenState extends State<SimpleSyncSettingsScreen> {
} else if (cleanUrl.startsWith('https://')) {
cleanUrl = cleanUrl.substring(8);
}
// Remove trailing slash if present
if (cleanUrl.endsWith('/')) {
cleanUrl = cleanUrl.substring(0, cleanUrl.length - 1);
}
// For Nextcloud instances, construct the standard WebDAV path
// Default to HTTPS for security
return 'https://$cleanUrl/remote.php/dav/files/$username/';
}
Widget _buildAutoSyncStatusIndicator(SimpleSyncProvider syncProvider) {
return Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
// Only show auto-sync status if auto-sync is enabled
if (!settingsProvider.autoSyncEnabled) {
return const SizedBox.shrink();
}
// Check if auto-sync service has pending sync
final autoSyncService = syncProvider.autoSyncService;
if (autoSyncService == null) {
return const SizedBox.shrink();
}
// Show pending auto-sync indicator
if (autoSyncService.hasPendingSync && !syncProvider.isSyncing) {
return Container(
margin: const EdgeInsets.only(top: 8),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: Colors.blue.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(16),
border: Border.all(color: Colors.blue.withValues(alpha: 0.3)),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
width: 12,
height: 12,
child: CircularProgressIndicator(
strokeWidth: 1.5,
valueColor: const AlwaysStoppedAnimation<Color>(Colors.blue),
),
),
const SizedBox(width: 8),
Text(
'Auto-sync pending...',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Colors.blue,
fontWeight: FontWeight.w500,
),
),
],
),
);
}
// Show auto-sync active indicator (when sync is running and it's auto-triggered)
if (syncProvider.isSyncing && syncProvider.isAutoSync) {
return Container(
margin: const EdgeInsets.only(top: 8),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: Colors.deepOrange.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(16),
border: Border.all(color: Colors.deepOrange.withValues(alpha: 0.3)),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.sync_alt,
size: 12,
color: Colors.deepOrange,
),
const SizedBox(width: 8),
Text(
'Auto-sync active',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Colors.deepOrange,
fontWeight: FontWeight.w500,
),
),
],
),
);
}
return const SizedBox.shrink();
},
);
}
Widget _buildAutoSyncStatusBadge(SettingsProvider settingsProvider, SimpleSyncProvider syncProvider) {
if (!settingsProvider.autoSyncEnabled) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: Colors.grey.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(8),
),
child: Text(
'OFF',
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: Colors.grey[600],
fontWeight: FontWeight.w600,
),
),
);
}
// Check if auto-sync is disabled due to errors
if (syncProvider.isAutoSyncDisabledDueToErrors) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: Colors.red.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(8),
),
child: Text(
'ERROR',
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: Colors.red[700],
fontWeight: FontWeight.w600,
),
),
);
}
// Check if sync is configured
if (!syncProvider.isConfigured) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: Colors.orange.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(8),
),
child: Text(
'NOT CONFIGURED',
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: Colors.orange[700],
fontWeight: FontWeight.w600,
),
),
);
}
// Check if there are recent failures but not disabled yet
if (syncProvider.autoSyncConsecutiveFailures > 0) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: Colors.orange.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(8),
),
child: Text(
'RETRYING',
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: Colors.orange[700],
fontWeight: FontWeight.w600,
),
),
);
}
return Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: Colors.green.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(8),
),
child: Text(
'ACTIVE',
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: Colors.green[700],
fontWeight: FontWeight.w600,
),
),
);
}
String _getErrorMessage(SimpleSyncProvider syncProvider) {
final error = syncProvider.lastError ?? 'Unknown error';
// Add context for auto-sync errors
if (syncProvider.isAutoSync) {
return 'Auto-sync error: $error';
}
return error;
}
String _formatDateTime(DateTime dateTime) {
return '${dateTime.day}/${dateTime.month}/${dateTime.year} ${dateTime.hour}:${dateTime.minute.toString().padLeft(2, '0')}';
}

View File

@@ -0,0 +1,470 @@
import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'package:flutter/foundation.dart';
import '../providers/settings_provider.dart';
import '../providers/simple_sync_provider.dart';
/// Error types for auto-sync operations
enum AutoSyncErrorType {
network,
configuration,
authentication,
server,
unknown,
}
/// Represents an auto-sync error with context
class AutoSyncError {
final AutoSyncErrorType type;
final String message;
final DateTime timestamp;
final dynamic originalError;
AutoSyncError({
required this.type,
required this.message,
required this.timestamp,
this.originalError,
});
@override
String toString() => 'AutoSyncError($type): $message';
}
/// Service that handles automatic synchronization with debouncing logic
/// to prevent excessive sync requests when multiple data changes occur rapidly.
class AutoSyncService {
Timer? _debounceTimer;
bool _syncInProgress = false;
bool _hasPendingSync = false;
// Error handling and retry logic
final List<AutoSyncError> _recentErrors = [];
int _consecutiveFailures = 0;
DateTime? _lastFailureTime;
Timer? _retryTimer;
bool _autoDisabledDueToErrors = false;
// Exponential backoff configuration
static const int _maxRetryAttempts = 5;
static const int _baseRetryDelaySeconds = 30;
static const int _maxRetryDelaySeconds = 300; // 5 minutes
static const int _errorHistoryMaxSize = 10;
static const int _autoDisableThreshold = 3; // Consecutive failures before auto-disable
final SimpleSyncProvider _syncProvider;
final SettingsProvider _settingsProvider;
AutoSyncService({
required SimpleSyncProvider syncProvider,
required SettingsProvider settingsProvider,
}) : _syncProvider = syncProvider,
_settingsProvider = settingsProvider;
/// Triggers an auto-sync if enabled in settings.
/// Uses debouncing to prevent excessive sync requests.
void triggerAutoSync() {
// Check if auto-sync is enabled
if (!_settingsProvider.autoSyncEnabled) {
if (kDebugMode) {
print('AutoSyncService: Auto-sync is disabled, skipping trigger');
}
return;
}
// Check if auto-sync was disabled due to persistent errors
if (_autoDisabledDueToErrors) {
if (kDebugMode) {
print('AutoSyncService: Auto-sync disabled due to persistent errors, skipping trigger');
}
return;
}
// Check if sync is configured
if (!_syncProvider.isConfigured) {
_recordError(AutoSyncError(
type: AutoSyncErrorType.configuration,
message: 'Sync not configured. Please configure cloud sync settings.',
timestamp: DateTime.now(),
));
if (kDebugMode) {
print('AutoSyncService: Sync not configured, skipping auto-sync');
}
return;
}
// If sync is already in progress, mark that we have a pending sync
if (_syncInProgress || _syncProvider.isSyncing) {
_hasPendingSync = true;
if (kDebugMode) {
print('AutoSyncService: Sync in progress, marking pending sync');
}
return;
}
// Cancel existing timer if one is running
_cancelPendingSync();
// Check if we should apply exponential backoff
final backoffDelay = _calculateBackoffDelay();
if (backoffDelay > 0) {
if (kDebugMode) {
print('AutoSyncService: Applying backoff delay of ${backoffDelay}s due to recent failures');
}
_debounceTimer = Timer(Duration(seconds: backoffDelay), () {
_executePendingSync();
});
return;
}
// Start new debounce timer
final debounceSeconds = _settingsProvider.autoSyncDebounceSeconds;
_debounceTimer = Timer(Duration(seconds: debounceSeconds), () {
_executePendingSync();
});
if (kDebugMode) {
print('AutoSyncService: Auto-sync scheduled in ${debounceSeconds}s');
}
}
/// Executes the pending sync operation
Future<void> _executePendingSync() async {
// Double-check conditions before executing
if (!_settingsProvider.autoSyncEnabled) {
if (kDebugMode) {
print('AutoSyncService: Auto-sync disabled during execution, aborting');
}
return;
}
if (_autoDisabledDueToErrors) {
if (kDebugMode) {
print('AutoSyncService: Auto-sync disabled due to errors during execution, aborting');
}
return;
}
if (!_syncProvider.isConfigured) {
_recordError(AutoSyncError(
type: AutoSyncErrorType.configuration,
message: 'Sync not configured during execution',
timestamp: DateTime.now(),
));
if (kDebugMode) {
print('AutoSyncService: Sync not configured during execution, aborting');
}
return;
}
if (_syncInProgress || _syncProvider.isSyncing) {
if (kDebugMode) {
print('AutoSyncService: Sync already in progress during execution, aborting');
}
return;
}
_syncInProgress = true;
_hasPendingSync = false;
try {
if (kDebugMode) {
print('AutoSyncService: Executing auto-sync (attempt ${_consecutiveFailures + 1})');
}
// Check network connectivity before attempting sync
if (!await _isNetworkAvailable()) {
throw AutoSyncError(
type: AutoSyncErrorType.network,
message: 'Network is not available',
timestamp: DateTime.now(),
);
}
await _syncProvider.syncDatabase(isAutoSync: true);
// Reset failure count on successful sync
_consecutiveFailures = 0;
_lastFailureTime = null;
_autoDisabledDueToErrors = false;
if (kDebugMode) {
print('AutoSyncService: Auto-sync completed successfully');
}
} catch (e) {
if (kDebugMode) {
print('AutoSyncService: Auto-sync failed: $e');
}
// Handle specific error types
_handleSyncError(e);
} finally {
_syncInProgress = false;
// If there was a pending sync request while we were syncing, trigger it
if (_hasPendingSync && !_autoDisabledDueToErrors) {
if (kDebugMode) {
print('AutoSyncService: Processing queued sync request');
}
_hasPendingSync = false;
// Use a small delay to avoid immediate re-triggering
Timer(const Duration(milliseconds: 500), () {
triggerAutoSync();
});
}
}
}
/// Handles sync errors with appropriate recovery strategies
void _handleSyncError(dynamic error) {
_consecutiveFailures++;
_lastFailureTime = DateTime.now();
final autoSyncError = _categorizeError(error);
_recordError(autoSyncError);
// Check if we should disable auto-sync due to persistent errors
if (_consecutiveFailures >= _autoDisableThreshold) {
_autoDisabledDueToErrors = true;
if (kDebugMode) {
print('AutoSyncService: Auto-sync disabled due to ${_consecutiveFailures} consecutive failures');
}
// For configuration errors, disable immediately
if (autoSyncError.type == AutoSyncErrorType.configuration ||
autoSyncError.type == AutoSyncErrorType.authentication) {
if (kDebugMode) {
print('AutoSyncService: Auto-sync disabled due to configuration/authentication error');
}
}
}
// Schedule retry for recoverable errors (unless auto-disabled)
if (!_autoDisabledDueToErrors && _shouldRetry(autoSyncError.type)) {
_scheduleRetry();
}
}
/// Categorizes an error into a specific AutoSyncError type
AutoSyncError _categorizeError(dynamic error) {
final errorString = error.toString().toLowerCase();
// Network-related errors
if (error is SocketException ||
errorString.contains('network') ||
errorString.contains('connection') ||
errorString.contains('timeout') ||
errorString.contains('unreachable') ||
errorString.contains('host lookup failed') ||
errorString.contains('no route to host')) {
return AutoSyncError(
type: AutoSyncErrorType.network,
message: 'Network connection failed. Check your internet connection.',
timestamp: DateTime.now(),
originalError: error,
);
}
// Configuration-related errors
if (errorString.contains('not configured') ||
errorString.contains('invalid url') ||
errorString.contains('malformed url')) {
return AutoSyncError(
type: AutoSyncErrorType.configuration,
message: 'Sync configuration is invalid. Please check your sync settings.',
timestamp: DateTime.now(),
originalError: error,
);
}
// Authentication errors
if (errorString.contains('authentication') ||
errorString.contains('unauthorized') ||
errorString.contains('401') ||
errorString.contains('403') ||
errorString.contains('invalid credentials')) {
return AutoSyncError(
type: AutoSyncErrorType.authentication,
message: 'Authentication failed. Please check your username and password.',
timestamp: DateTime.now(),
originalError: error,
);
}
// Server errors
if (errorString.contains('500') ||
errorString.contains('502') ||
errorString.contains('503') ||
errorString.contains('504') ||
errorString.contains('server error')) {
return AutoSyncError(
type: AutoSyncErrorType.server,
message: 'Server error occurred. The sync server may be temporarily unavailable.',
timestamp: DateTime.now(),
originalError: error,
);
}
// Unknown errors
return AutoSyncError(
type: AutoSyncErrorType.unknown,
message: 'An unexpected error occurred during sync: ${error.toString()}',
timestamp: DateTime.now(),
originalError: error,
);
}
/// Records an error in the recent errors list
void _recordError(AutoSyncError error) {
_recentErrors.add(error);
// Keep only recent errors
if (_recentErrors.length > _errorHistoryMaxSize) {
_recentErrors.removeAt(0);
}
if (kDebugMode) {
print('AutoSyncService: Recorded error: $error');
}
}
/// Determines if we should retry for a given error type
bool _shouldRetry(AutoSyncErrorType errorType) {
switch (errorType) {
case AutoSyncErrorType.network:
case AutoSyncErrorType.server:
return _consecutiveFailures < _maxRetryAttempts;
case AutoSyncErrorType.configuration:
case AutoSyncErrorType.authentication:
return false; // Don't retry config/auth errors
case AutoSyncErrorType.unknown:
return _consecutiveFailures < _maxRetryAttempts;
}
}
/// Calculates the backoff delay based on consecutive failures
int _calculateBackoffDelay() {
if (_consecutiveFailures == 0 || _lastFailureTime == null) {
return 0;
}
// Calculate exponential backoff: base * (2^failures)
final backoffSeconds = min(
_baseRetryDelaySeconds * pow(2, _consecutiveFailures - 1).toInt(),
_maxRetryDelaySeconds,
);
// Check if enough time has passed since last failure
final timeSinceLastFailure = DateTime.now().difference(_lastFailureTime!).inSeconds;
if (timeSinceLastFailure >= backoffSeconds) {
return 0; // No additional delay needed
}
return backoffSeconds - timeSinceLastFailure;
}
/// Schedules a retry attempt with exponential backoff
void _scheduleRetry() {
final retryDelay = _calculateBackoffDelay();
if (retryDelay <= 0) return;
_retryTimer?.cancel();
_retryTimer = Timer(Duration(seconds: retryDelay), () {
if (kDebugMode) {
print('AutoSyncService: Retrying auto-sync after backoff delay');
}
triggerAutoSync();
});
if (kDebugMode) {
print('AutoSyncService: Scheduled retry in ${retryDelay}s');
}
}
/// Checks if network is available
Future<bool> _isNetworkAvailable() async {
try {
final result = await InternetAddress.lookup('google.com');
return result.isNotEmpty && result[0].rawAddress.isNotEmpty;
} catch (e) {
if (kDebugMode) {
print('AutoSyncService: Network check failed: $e');
}
return false;
}
}
/// Cancels any pending sync operation
void cancelPendingSync() {
_cancelPendingSync();
_retryTimer?.cancel();
_retryTimer = null;
_hasPendingSync = false;
if (kDebugMode) {
print('AutoSyncService: Cancelled pending sync and retry timer');
}
}
/// Internal method to cancel the debounce timer
void _cancelPendingSync() {
_debounceTimer?.cancel();
_debounceTimer = null;
}
/// Resets error state and re-enables auto-sync if it was disabled
void resetErrorState() {
_consecutiveFailures = 0;
_lastFailureTime = null;
_autoDisabledDueToErrors = false;
_recentErrors.clear();
_retryTimer?.cancel();
_retryTimer = null;
if (kDebugMode) {
print('AutoSyncService: Error state reset, auto-sync re-enabled');
}
}
/// Disposes of the service and cleans up resources
void dispose() {
_cancelPendingSync();
_retryTimer?.cancel();
_retryTimer = null;
_hasPendingSync = false;
_syncInProgress = false;
_recentErrors.clear();
if (kDebugMode) {
print('AutoSyncService: Disposed');
}
}
/// Returns true if there is a pending sync operation
bool get hasPendingSync => _hasPendingSync || _debounceTimer != null;
/// Returns true if a sync is currently in progress
bool get isSyncInProgress => _syncInProgress;
/// Returns true if auto-sync was disabled due to persistent errors
bool get isAutoDisabledDueToErrors => _autoDisabledDueToErrors;
/// Returns the number of consecutive failures
int get consecutiveFailures => _consecutiveFailures;
/// Returns a copy of recent errors
List<AutoSyncError> get recentErrors => List.unmodifiable(_recentErrors);
/// Returns the last error message suitable for display to users
String? get lastErrorMessage {
if (_recentErrors.isEmpty) return null;
return _recentErrors.last.message;
}
/// Returns true if a retry is currently scheduled
bool get hasScheduledRetry => _retryTimer != null;
}

View File

@@ -27,40 +27,40 @@ enum RecordSyncStatus {
class DatabaseSyncService {
static const String _remoteDbFileName = 'supplements.db';
// SharedPreferences keys for persistence
static const String _keyServerUrl = 'sync_server_url';
static const String _keyUsername = 'sync_username';
static const String _keyPassword = 'sync_password';
static const String _keyRemotePath = 'sync_remote_path';
Client? _client;
String? _remotePath;
// Store configuration values
String? _serverUrl;
String? _username;
String? _username;
String? _password;
String? _configuredRemotePath;
final DatabaseHelper _databaseHelper = DatabaseHelper.instance;
SyncStatus _status = SyncStatus.idle;
String? _lastError;
DateTime? _lastSyncTime;
// Getters
SyncStatus get status => _status;
String? get lastError => _lastError;
DateTime? get lastSyncTime => _lastSyncTime;
bool get isConfigured => _client != null;
// Configuration getters
String? get serverUrl => _serverUrl;
String? get username => _username;
String? get password => _password;
String? get remotePath => _configuredRemotePath;
// Callbacks for UI updates
Function(SyncStatus)? onStatusChanged;
Function(String)? onError;
@@ -78,11 +78,11 @@ class DatabaseSyncService {
_username = prefs.getString(_keyUsername);
_password = prefs.getString(_keyPassword);
_configuredRemotePath = prefs.getString(_keyRemotePath);
// If we have saved configuration, set up the client
if (_serverUrl != null && _username != null && _password != null && _configuredRemotePath != null) {
_remotePath = _configuredRemotePath!.endsWith('/') ? _configuredRemotePath : '$_configuredRemotePath/';
_client = newClient(
_serverUrl!,
user: _username!,
@@ -123,9 +123,9 @@ class DatabaseSyncService {
_username = username;
_password = password;
_configuredRemotePath = remotePath;
_remotePath = remotePath.endsWith('/') ? remotePath : '$remotePath/';
_client = newClient(
serverUrl,
user: username,
@@ -139,7 +139,7 @@ class DatabaseSyncService {
Future<bool> testConnection() async {
if (_client == null) return false;
try {
await _client!.ping();
return true;
@@ -157,26 +157,26 @@ class DatabaseSyncService {
}
_setStatus(SyncStatus.downloading);
try {
// Step 1: Download remote database (if it exists)
final remoteDbPath = await _downloadRemoteDatabase();
// Step 2: Merge databases
_setStatus(SyncStatus.merging);
await _mergeDatabases(remoteDbPath);
// Step 3: Upload merged database
_setStatus(SyncStatus.uploading);
await _uploadLocalDatabase();
// Step 4: Cleanup - for now we'll skip cleanup to avoid file issues
// TODO: Implement proper cleanup once file operations are working
_lastSyncTime = DateTime.now();
_setStatus(SyncStatus.completed);
onSyncCompleted?.call();
} catch (e) {
_lastError = e.toString();
_setStatus(SyncStatus.error);
@@ -193,35 +193,35 @@ class DatabaseSyncService {
// Check if remote database exists
final files = await _client!.readDir(_remotePath!);
final remoteDbExists = files.any((file) => file.name == _remoteDbFileName);
if (!remoteDbExists) {
if (kDebugMode) {
print('SupplementsLog: No remote database found, will upload local database');
}
return null;
}
if (kDebugMode) {
print('SupplementsLog: Remote database found, downloading...');
}
// Download the remote database
final remoteDbBytes = await _client!.read('$_remotePath$_remoteDbFileName');
// Create a temporary file path for the downloaded database
final tempDir = await getDatabasesPath();
final tempDbPath = join(tempDir, 'remote_supplements.db');
// Write the downloaded database to a temporary file
final tempFile = io.File(tempDbPath);
await tempFile.writeAsBytes(remoteDbBytes);
if (kDebugMode) {
print('SupplementsLog: Downloaded remote database (${remoteDbBytes.length} bytes) to: $tempDbPath');
}
return tempDbPath;
} catch (e) {
if (kDebugMode) {
print('SupplementsLog: Failed to download remote database: $e');
@@ -237,20 +237,20 @@ class DatabaseSyncService {
}
return;
}
if (kDebugMode) {
print('SupplementsLog: Starting database merge from: $remoteDbPath');
}
final localDb = await _databaseHelper.database;
final remoteDb = await openDatabase(remoteDbPath, readOnly: true);
try {
// Check what tables exist in remote database
if (kDebugMode) {
final tables = await remoteDb.rawQuery("SELECT name FROM sqlite_master WHERE type='table'");
print('SupplementsLog: Remote database tables: ${tables.map((t) => t['name']).toList()}');
// Count records in each table
try {
final supplementCount = await remoteDb.rawQuery('SELECT COUNT(*) as count FROM supplements');
@@ -258,7 +258,7 @@ class DatabaseSyncService {
} catch (e) {
print('SupplementsLog: Error counting supplements: $e');
}
try {
final intakeCount = await remoteDb.rawQuery('SELECT COUNT(*) as count FROM supplement_intakes');
print('SupplementsLog: Remote intakes count: ${intakeCount.first['count']}');
@@ -266,17 +266,17 @@ class DatabaseSyncService {
print('SupplementsLog: Error counting intakes: $e');
}
}
// Merge supplements
await _mergeSupplements(localDb, remoteDb);
// Merge intakes
await _mergeIntakes(localDb, remoteDb);
if (kDebugMode) {
print('SupplementsLog: Database merge completed successfully');
}
} finally {
await remoteDb.close();
}
@@ -286,52 +286,62 @@ class DatabaseSyncService {
if (kDebugMode) {
print('SupplementsLog: Starting supplement merge...');
}
// Get all supplements from remote database
final remoteMaps = await remoteDb.query('supplements');
final remoteSupplements = remoteMaps.map((map) => Supplement.fromMap(map)).toList();
final remoteSupplements =
remoteMaps.map((map) => Supplement.fromMap(map)).toList();
if (kDebugMode) {
print('SupplementsLog: Found ${remoteSupplements.length} supplements in remote database');
print(
'SupplementsLog: Found ${remoteSupplements.length} supplements in remote database');
for (final supplement in remoteSupplements) {
print('SupplementsLog: Remote supplement: ${supplement.name} (syncId: ${supplement.syncId}, deleted: ${supplement.isDeleted})');
print(
'SupplementsLog: Remote supplement: ${supplement.name} (syncId: ${supplement.syncId}, deleted: ${supplement.isDeleted})');
}
}
for (final remoteSupplement in remoteSupplements) {
if (remoteSupplement.syncId.isEmpty) {
if (kDebugMode) {
print('SupplementsLog: Skipping supplement ${remoteSupplement.name} - no syncId');
print(
'SupplementsLog: Skipping supplement ${remoteSupplement.name} - no syncId');
}
continue;
}
// Find existing supplement by syncId
final existingMaps = await localDb.query(
'supplements',
where: 'syncId = ?',
whereArgs: [remoteSupplement.syncId],
);
if (existingMaps.isEmpty) {
// New supplement from remote - insert it
if (!remoteSupplement.isDeleted) {
final supplementToInsert = remoteSupplement.copyWith(id: null);
await localDb.insert('supplements', supplementToInsert.toMap());
// Manually create a new map without the id to ensure it's null
final mapToInsert = remoteSupplement.toMap();
mapToInsert.remove('id');
await localDb.insert('supplements', mapToInsert);
if (kDebugMode) {
print('SupplementsLog: ✓ Inserted new supplement: ${remoteSupplement.name}');
print(
'SupplementsLog: ✓ Inserted new supplement: ${remoteSupplement.name}');
}
} else {
if (kDebugMode) {
print('SupplementsLog: Skipping deleted supplement: ${remoteSupplement.name}');
print(
'SupplementsLog: Skipping deleted supplement: ${remoteSupplement.name}');
}
}
} else {
// Existing supplement - update if remote is newer
final existingSupplement = Supplement.fromMap(existingMaps.first);
if (remoteSupplement.lastModified.isAfter(existingSupplement.lastModified)) {
final supplementToUpdate = remoteSupplement.copyWith(id: existingSupplement.id);
if (remoteSupplement.lastModified
.isAfter(existingSupplement.lastModified)) {
final supplementToUpdate =
remoteSupplement.copyWith(id: existingSupplement.id);
await localDb.update(
'supplements',
supplementToUpdate.toMap(),
@@ -339,16 +349,18 @@ class DatabaseSyncService {
whereArgs: [existingSupplement.id],
);
if (kDebugMode) {
print('SupplementsLog: ✓ Updated supplement: ${remoteSupplement.name}');
print(
'SupplementsLog: ✓ Updated supplement: ${remoteSupplement.name}');
}
} else {
if (kDebugMode) {
print('SupplementsLog: Local supplement ${remoteSupplement.name} is newer, keeping local version');
print(
'SupplementsLog: Local supplement ${remoteSupplement.name} is newer, keeping local version');
}
}
}
}
if (kDebugMode) {
print('SupplementsLog: Supplement merge completed');
}
@@ -358,15 +370,15 @@ class DatabaseSyncService {
if (kDebugMode) {
print('SupplementsLog: Starting intake merge...');
}
// Get all intakes from remote database
final remoteMaps = await remoteDb.query('supplement_intakes');
final remoteIntakes = remoteMaps.map((map) => SupplementIntake.fromMap(map)).toList();
if (kDebugMode) {
print('SupplementsLog: Found ${remoteIntakes.length} intakes in remote database');
}
for (final remoteIntake in remoteIntakes) {
if (remoteIntake.syncId.isEmpty) {
if (kDebugMode) {
@@ -374,14 +386,14 @@ class DatabaseSyncService {
}
continue;
}
// Find existing intake by syncId
final existingMaps = await localDb.query(
'supplement_intakes',
where: 'syncId = ?',
whereArgs: [remoteIntake.syncId],
);
if (existingMaps.isEmpty) {
// New intake from remote - need to find local supplement ID
if (!remoteIntake.isDeleted) {
@@ -408,7 +420,7 @@ class DatabaseSyncService {
} else {
// Existing intake - update if remote is newer
final existingIntake = SupplementIntake.fromMap(existingMaps.first);
if (remoteIntake.lastModified.isAfter(existingIntake.lastModified)) {
final intakeToUpdate = remoteIntake.copyWith(id: existingIntake.id);
await localDb.update(
@@ -427,7 +439,7 @@ class DatabaseSyncService {
}
}
}
if (kDebugMode) {
print('SupplementsLog: Intake merge completed');
}
@@ -440,20 +452,20 @@ class DatabaseSyncService {
where: 'id = ?',
whereArgs: [remoteSupplementId],
);
if (remoteSupplementMaps.isEmpty) return null;
final remoteSupplement = Supplement.fromMap(remoteSupplementMaps.first);
// Find the local supplement with the same syncId
final localSupplementMaps = await localDb.query(
'supplements',
where: 'syncId = ?',
whereArgs: [remoteSupplement.syncId],
);
if (localSupplementMaps.isEmpty) return null;
return localSupplementMaps.first['id'] as int;
}
@@ -462,27 +474,27 @@ class DatabaseSyncService {
// Get the local database path
final localDb = await _databaseHelper.database;
final dbPath = localDb.path;
if (kDebugMode) {
print('SupplementsLog: Reading database from: $dbPath');
}
// Read the database file
final dbFile = io.File(dbPath);
if (!await dbFile.exists()) {
throw Exception('Database file not found at: $dbPath');
}
final dbBytes = await dbFile.readAsBytes();
if (kDebugMode) {
print('SupplementsLog: Database file size: ${dbBytes.length} bytes');
}
if (dbBytes.isEmpty) {
throw Exception('Database file is empty');
}
// Ensure remote directory exists
try {
await _client!.readDir(_remotePath!);
@@ -492,15 +504,15 @@ class DatabaseSyncService {
}
await _client!.mkdir(_remotePath!);
}
// Upload the database file
final remoteUrl = '$_remotePath$_remoteDbFileName';
await _client!.write(remoteUrl, dbBytes);
if (kDebugMode) {
print('SupplementsLog: Successfully uploaded database (${dbBytes.length} bytes) to: $remoteUrl');
}
} catch (e) {
if (kDebugMode) {
print('SupplementsLog: Failed to upload database: $e');

View File

@@ -12,7 +12,7 @@ void notificationTapBackground(NotificationResponse notificationResponse) {
print('SupplementsLog: 📱 Payload: ${notificationResponse.payload}');
print('SupplementsLog: 📱 Notification ID: ${notificationResponse.id}');
print('SupplementsLog: 📱 ==========================================');
// For now, just log the action. The main app handler will process it.
if (notificationResponse.actionId == 'take_supplement') {
print('SupplementsLog: 📱 BACKGROUND: Take action detected');
@@ -30,7 +30,7 @@ class NotificationService {
bool _isInitialized = false;
static bool _engineInitialized = false;
bool _permissionsRequested = false;
// Callback for handling supplement intake from notifications
Function(int supplementId, String supplementName, double units, String unitType)? _onTakeSupplementCallback;
@@ -45,11 +45,11 @@ class NotificationService {
print('SupplementsLog: 📱 Already initialized');
return;
}
try {
print('SupplementsLog: 📱 Initializing timezones...');
print('SupplementsLog: 📱 Engine initialized flag: $_engineInitialized');
if (!_engineInitialized) {
tz.initializeTimeZones();
_engineInitialized = true;
@@ -61,15 +61,15 @@ class NotificationService {
print('SupplementsLog: 📱 Warning: Timezone initialization issue (may already be initialized): $e');
_engineInitialized = true; // Mark as initialized to prevent retry
}
// Try to detect and set the local timezone more reliably
try {
// First try using the system timezone name
final String timeZoneName = DateTime.now().timeZoneName;
print('SupplementsLog: 📱 System timezone name: $timeZoneName');
tz.Location? location;
// Try common timezone mappings for your region
if (timeZoneName.contains('CET') || timeZoneName.contains('CEST')) {
location = tz.getLocation('Europe/Amsterdam'); // Netherlands
@@ -84,19 +84,19 @@ class NotificationService {
location = tz.getLocation('Europe/Amsterdam');
}
}
tz.setLocalLocation(location);
print('SupplementsLog: 📱 Timezone set to: ${location.name}');
} catch (e) {
print('SupplementsLog: 📱 Error setting timezone: $e, using default');
// Fallback to a reasonable default for Netherlands
tz.setLocalLocation(tz.getLocation('Europe/Amsterdam'));
}
print('SupplementsLog: 📱 Current local time: ${tz.TZDateTime.now(tz.local)}');
print('SupplementsLog: 📱 Current system time: ${DateTime.now()}');
const AndroidInitializationSettings androidSettings = AndroidInitializationSettings('@mipmap/ic_launcher');
const DarwinInitializationSettings iosSettings = DarwinInitializationSettings(
requestAlertPermission: false, // We'll request these separately
@@ -119,10 +119,10 @@ class NotificationService {
onDidReceiveNotificationResponse: _onNotificationResponse,
onDidReceiveBackgroundNotificationResponse: notificationTapBackground,
);
// Test if notification response callback is working
print('SupplementsLog: 📱 Callback function is set and ready');
_isInitialized = true;
print('SupplementsLog: 📱 NotificationService initialization complete');
}
@@ -135,7 +135,7 @@ class NotificationService {
print('SupplementsLog: 📱 Notification ID: ${response.id}');
print('SupplementsLog: 📱 Input: ${response.input}');
print('SupplementsLog: 📱 ===============================');
if (response.actionId == 'take_supplement') {
print('SupplementsLog: 📱 Processing TAKE action...');
_handleTakeAction(response.payload, response.id);
@@ -151,43 +151,58 @@ class NotificationService {
Future<void> _handleTakeAction(String? payload, int? notificationId) async {
print('SupplementsLog: 📱 === HANDLING TAKE ACTION ===');
print('SupplementsLog: 📱 Payload received: $payload');
if (payload != null) {
try {
// Parse the payload to get supplement info
final parts = payload.split('|');
print('SupplementsLog: 📱 Payload parts: $parts (length: ${parts.length})');
if (parts.length >= 4) {
final supplementId = int.parse(parts[0]);
final supplementName = parts[1];
final units = double.parse(parts[2]);
final unitType = parts[3];
print('SupplementsLog: 📱 Parsed data:');
print('SupplementsLog: 📱 - ID: $supplementId');
print('SupplementsLog: 📱 - Name: $supplementName');
print('SupplementsLog: 📱 - Units: $units');
print('SupplementsLog: 📱 - Type: $unitType');
// Call the callback to record the intake
if (_onTakeSupplementCallback != null) {
print('SupplementsLog: 📱 Calling supplement callback...');
_onTakeSupplementCallback!(supplementId, supplementName, units, unitType);
_onTakeSupplementCallback!(
supplementId, supplementName, units, unitType);
print('SupplementsLog: 📱 Callback completed');
} else {
print('SupplementsLog: 📱 ERROR: No callback registered!');
}
// Mark notification as taken in database (this will cancel any pending retries)
if (notificationId != null) {
print('SupplementsLog: 📱 Marking notification $notificationId as taken');
await DatabaseHelper.instance.markNotificationTaken(notificationId);
// Cancel any pending retry notifications for this notification
_cancelRetryNotifications(notificationId);
// For retry notifications, the original notification ID is in the payload
int originalNotificationId;
if (parts.length > 4 && int.tryParse(parts[4]) != null) {
originalNotificationId = int.parse(parts[4]);
print(
'SupplementsLog: 📱 Retry notification detected. Original ID: $originalNotificationId');
} else if (notificationId != null) {
originalNotificationId = notificationId;
} else {
print(
'SupplementsLog: 📱 ERROR: Could not determine notification ID to cancel.');
return;
}
// Mark notification as taken in database (this will cancel any pending retries)
print(
'SupplementsLog: 📱 Marking notification $originalNotificationId as taken');
await DatabaseHelper.instance
.markNotificationTaken(originalNotificationId);
// Cancel any pending retry notifications for this notification
_cancelRetryNotifications(originalNotificationId);
// Show a confirmation notification
print('SupplementsLog: 📱 Showing confirmation notification...');
showInstantNotification(
@@ -195,7 +210,8 @@ class NotificationService {
'$supplementName has been recorded at ${DateTime.now().hour.toString().padLeft(2, '0')}:${DateTime.now().minute.toString().padLeft(2, '0')}',
);
} else {
print('SupplementsLog: 📱 ERROR: Invalid payload format - not enough parts');
print(
'SupplementsLog: 📱 ERROR: Invalid payload format - not enough parts');
}
} catch (e) {
print('SupplementsLog: 📱 ERROR in _handleTakeAction: $e');
@@ -218,26 +234,26 @@ class NotificationService {
void _handleSnoozeAction(String? payload, int minutes, int? notificationId) {
print('SupplementsLog: 📱 === HANDLING SNOOZE ACTION ===');
print('SupplementsLog: 📱 Payload: $payload, Minutes: $minutes');
if (payload != null) {
try {
final parts = payload.split('|');
if (parts.length >= 2) {
final supplementId = int.parse(parts[0]);
final supplementName = parts[1];
print('SupplementsLog: 📱 Snoozing supplement for $minutes minutes: $supplementName');
// Mark notification as snoozed in database (increment retry count)
if (notificationId != null) {
print('SupplementsLog: 📱 Incrementing retry count for notification $notificationId');
DatabaseHelper.instance.incrementRetryCount(notificationId);
}
// Schedule a new notification for the snooze time
final snoozeTime = tz.TZDateTime.now(tz.local).add(Duration(minutes: minutes));
print('SupplementsLog: 📱 Snooze time: $snoozeTime');
_notifications.zonedSchedule(
supplementId * 1000 + minutes, // Unique ID for snooze notifications
'Reminder: $supplementName',
@@ -266,7 +282,7 @@ class NotificationService {
androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
payload: payload,
);
showInstantNotification(
'Reminder Snoozed',
'$supplementName reminder snoozed for $minutes minutes',
@@ -300,32 +316,32 @@ class NotificationService {
required int maxRetryAttempts,
}) async {
print('SupplementsLog: 📱 Checking for pending notifications to retry...');
try {
if (!persistentReminders) {
print('SupplementsLog: 📱 Persistent reminders disabled');
return;
}
print('SupplementsLog: 📱 Retry settings: interval=$reminderRetryInterval min, max=$maxRetryAttempts attempts');
// Get all pending notifications from database
final pendingNotifications = await DatabaseHelper.instance.getPendingNotifications();
print('SupplementsLog: 📱 Found ${pendingNotifications.length} pending notifications');
final now = DateTime.now();
for (final notification in pendingNotifications) {
final scheduledTime = DateTime.parse(notification['scheduledTime']).toLocal();
final retryCount = notification['retryCount'] as int;
final lastRetryTime = notification['lastRetryTime'] != null
final lastRetryTime = notification['lastRetryTime'] != null
? DateTime.parse(notification['lastRetryTime']).toLocal()
: null;
// Check if notification is overdue
final timeSinceScheduled = now.difference(scheduledTime).inMinutes;
final shouldRetry = timeSinceScheduled >= reminderRetryInterval;
print('SupplementsLog: 📱 Checking notification ${notification['notificationId']}:');
print('SupplementsLog: 📱 Scheduled: $scheduledTime (local)');
print('SupplementsLog: 📱 Now: $now');
@@ -333,13 +349,13 @@ class NotificationService {
print('SupplementsLog: 📱 Retry interval: $reminderRetryInterval minutes');
print('SupplementsLog: 📱 Should retry: $shouldRetry');
print('SupplementsLog: 📱 Retry count: $retryCount / $maxRetryAttempts');
// Check if we haven't exceeded max retry attempts
if (retryCount >= maxRetryAttempts) {
print('SupplementsLog: 📱 Notification ${notification['notificationId']} exceeded max attempts ($maxRetryAttempts)');
continue;
}
// Check if enough time has passed since last retry
if (lastRetryTime != null) {
final timeSinceLastRetry = now.difference(lastRetryTime).inMinutes;
@@ -348,7 +364,7 @@ class NotificationService {
continue;
}
}
if (shouldRetry) {
print('SupplementsLog: 📱 ⚡ SCHEDULING RETRY for notification ${notification['notificationId']}');
await _scheduleRetryNotification(notification, retryCount + 1);
@@ -365,16 +381,16 @@ class NotificationService {
try {
final notificationId = notification['notificationId'] as int;
final supplementId = notification['supplementId'] as int;
// Generate a unique ID for this retry (200000 + original_id * 10 + retry_attempt)
final retryNotificationId = 200000 + (notificationId * 10) + retryAttempt;
print('SupplementsLog: 📱 Scheduling retry notification $retryNotificationId for supplement $supplementId (attempt $retryAttempt)');
// Get supplement details from database
final supplements = await DatabaseHelper.instance.getAllSupplements();
final supplement = supplements.firstWhere((s) => s.id == supplementId && s.isActive, orElse: () => throw Exception('Supplement not found'));
// Schedule the retry notification immediately
await _notifications.show(
retryNotificationId,
@@ -404,10 +420,10 @@ class NotificationService {
),
payload: '${supplement.id}|${supplement.name}|${supplement.numberOfUnits}|${supplement.unitType}|$notificationId',
);
// Update the retry count in database
await DatabaseHelper.instance.incrementRetryCount(notificationId);
print('SupplementsLog: 📱 Retry notification scheduled successfully');
} catch (e) {
print('SupplementsLog: 📱 Error scheduling retry notification: $e');
@@ -420,10 +436,10 @@ class NotificationService {
print('SupplementsLog: 📱 Permissions already requested');
return true;
}
try {
_permissionsRequested = true;
final androidPlugin = _notifications.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>();
if (androidPlugin != null) {
print('SupplementsLog: 📱 Requesting Android permissions...');
@@ -434,7 +450,7 @@ class NotificationService {
return false;
}
}
final iosPlugin = _notifications.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>();
if (iosPlugin != null) {
print('SupplementsLog: 📱 Requesting iOS permissions...');
@@ -449,7 +465,7 @@ class NotificationService {
return false;
}
}
print('SupplementsLog: 📱 All permissions granted successfully');
return true;
} catch (e) {
@@ -462,7 +478,7 @@ class NotificationService {
Future<void> scheduleSupplementReminders(Supplement supplement) async {
print('SupplementsLog: 📱 Scheduling reminders for ${supplement.name}');
print('SupplementsLog: 📱 Reminder times: ${supplement.reminderTimes}');
// Cancel existing notifications for this supplement
await cancelSupplementReminders(supplement.id!);
@@ -474,7 +490,7 @@ class NotificationService {
final notificationId = supplement.id! * 100 + i; // Unique ID for each reminder
final scheduledTime = _nextInstanceOfTime(hour, minute);
print('SupplementsLog: 📱 Scheduling notification ID $notificationId for ${timeStr} -> ${scheduledTime}');
// Track this notification in the database
@@ -505,7 +521,7 @@ class NotificationService {
),
AndroidNotificationAction(
'snooze_10',
'Snooze 10min',
'Snooze 10min',
icon: DrawableResourceAndroidBitmap('@android:drawable/ic_menu_recent_history'),
showsUserInterface: true, // Changed to true to open app
),
@@ -517,10 +533,10 @@ class NotificationService {
matchDateTimeComponents: DateTimeComponents.time,
payload: '${supplement.id}|${supplement.name}|${supplement.numberOfUnits}|${supplement.unitType}',
);
print('SupplementsLog: 📱 Successfully scheduled notification ID $notificationId');
}
// Get all pending notifications to verify
final pendingNotifications = await _notifications.pendingNotificationRequests();
print('SupplementsLog: 📱 Total pending notifications: ${pendingNotifications.length}');
@@ -535,7 +551,7 @@ class NotificationService {
final notificationId = supplementId * 100 + i;
await _notifications.cancel(notificationId);
}
// Also clean up database tracking records for this supplement
await DatabaseHelper.instance.clearNotificationTracking(supplementId);
}
@@ -547,18 +563,18 @@ class NotificationService {
tz.TZDateTime _nextInstanceOfTime(int hour, int minute) {
final tz.TZDateTime now = tz.TZDateTime.now(tz.local);
tz.TZDateTime scheduledDate = tz.TZDateTime(tz.local, now.year, now.month, now.day, hour, minute);
print('SupplementsLog: 📱 Current time: $now (${now.timeZoneName})');
print('SupplementsLog: 📱 Target time: ${hour.toString().padLeft(2, '0')}:${minute.toString().padLeft(2, '0')}');
print('SupplementsLog: 📱 Initial scheduled date: $scheduledDate (${scheduledDate.timeZoneName})');
if (scheduledDate.isBefore(now)) {
scheduledDate = scheduledDate.add(const Duration(days: 1));
print('SupplementsLog: 📱 Time has passed, scheduling for tomorrow: $scheduledDate (${scheduledDate.timeZoneName})');
} else {
print('SupplementsLog: 📱 Time is in the future, scheduling for today: $scheduledDate (${scheduledDate.timeZoneName})');
}
return scheduledDate;
}
@@ -595,9 +611,9 @@ class NotificationService {
print('SupplementsLog: 📱 Testing scheduled notification...');
final now = tz.TZDateTime.now(tz.local);
final testTime = now.add(const Duration(minutes: 1));
print('SupplementsLog: 📱 Scheduling test notification for: $testTime');
await _notifications.zonedSchedule(
99999, // Special ID for test notifications
'Test Scheduled Notification',
@@ -615,7 +631,7 @@ class NotificationService {
),
androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
);
print('SupplementsLog: 📱 Test notification scheduled successfully');
}
@@ -627,7 +643,7 @@ class NotificationService {
// Debug function to test notification actions
Future<void> testNotificationWithActions() async {
print('SupplementsLog: 📱 Creating test notification with actions...');
await _notifications.show(
88888, // Special test ID
'Test Action Notification',
@@ -658,14 +674,14 @@ class NotificationService {
),
payload: '999|Test Supplement|1.0|capsule',
);
print('SupplementsLog: 📱 Test notification with actions created');
}
// Debug function to test basic notification tap response
Future<void> testBasicNotification() async {
print('SupplementsLog: 📱 Creating basic test notification...');
await _notifications.show(
77777, // Special test ID for basic notification
'Basic Test Notification',
@@ -682,7 +698,7 @@ class NotificationService {
),
payload: 'basic_test',
);
print('SupplementsLog: 📱 Basic test notification created');
}
}

View File

@@ -1,7 +1,7 @@
name: supplements
description: "A supplement tracking app for managing your daily supplements"
publish_to: "none"
version: 1.0.3+27082025
version: 1.0.5+27082025
environment:
sdk: ^3.9.0

View File

@@ -1,30 +0,0 @@
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:supplements/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}