mirror of
https://github.com/vleeuwenmenno/supplements.git
synced 2025-12-08 14:05:56 +00:00
Compare commits
14 Commits
v1.0.2+270
...
62debb6a7c
| Author | SHA1 | Date | |
|---|---|---|---|
|
62debb6a7c
|
|||
|
f7966ce587
|
|||
|
811c1f3d6a
|
|||
|
6dccac6124
|
|||
|
9ae2bb5654
|
|||
|
31e04fe260
|
|||
|
6524e625d8
|
|||
|
142359bf94
|
|||
|
731ac1567d
|
|||
|
31e1b4f0bb
|
|||
|
40e7cc0461
|
|||
|
e95dcf3322
|
|||
|
33dfd6e3e5
|
|||
|
2017fd097d
|
9
.zed/debug.json
Normal file
9
.zed/debug.json
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"label": "Debug Flutter App",
|
||||||
|
"adapter": "Dart",
|
||||||
|
"type": "flutter",
|
||||||
|
"program": "lib/main.dart",
|
||||||
|
"args": ["--web-port=9090"]
|
||||||
|
}
|
||||||
|
]
|
||||||
@@ -1,287 +0,0 @@
|
|||||||
# WebDAV Cloud Sync Implementation
|
|
||||||
|
|
||||||
## Overview
|
|
||||||
|
|
||||||
This document describes the WebDAV cloud sync implementation for the Supplements Tracker Flutter app. The implementation allows users to synchronize their supplement data across multiple devices using WebDAV-compatible servers like Nextcloud, ownCloud, or any standard WebDAV server.
|
|
||||||
|
|
||||||
## Architecture
|
|
||||||
|
|
||||||
### Core Components
|
|
||||||
|
|
||||||
#### 1. Data Models Enhanced with Sync Metadata
|
|
||||||
|
|
||||||
All core data models (`Supplement`, `SupplementIntake`, `Ingredient`) have been enhanced with sync metadata:
|
|
||||||
|
|
||||||
- `syncId: String` - Unique identifier for sync operations (UUID)
|
|
||||||
- `lastModified: DateTime` - Timestamp of last modification
|
|
||||||
- `syncStatus: SyncStatus` - Current sync state (pending, synced, modified, conflict, etc.)
|
|
||||||
- `isDeleted: bool` - Soft delete flag for sync purposes
|
|
||||||
|
|
||||||
#### 2. Sync Enumerations (`lib/models/sync_enums.dart`)
|
|
||||||
|
|
||||||
- `SyncStatus` - Track individual record sync states
|
|
||||||
- `SyncOperationStatus` - Overall sync operation states
|
|
||||||
- `ConflictResolutionStrategy` - How to handle conflicts
|
|
||||||
- `SyncFrequency` - Auto-sync timing options
|
|
||||||
- `ConflictType` - Types of sync conflicts
|
|
||||||
|
|
||||||
#### 3. Sync Data Models (`lib/models/sync_data.dart`)
|
|
||||||
|
|
||||||
- `SyncData` - Complete data structure for WebDAV JSON format
|
|
||||||
- `SyncConflict` - Represents conflicts between local and remote data
|
|
||||||
- `SyncResult` - Results and statistics from sync operations
|
|
||||||
- `SyncStatistics` - Detailed sync operation metrics
|
|
||||||
|
|
||||||
#### 4. WebDAV Sync Service (`lib/services/webdav_sync_service.dart`)
|
|
||||||
|
|
||||||
Core service handling WebDAV communication:
|
|
||||||
- Server configuration and authentication
|
|
||||||
- Data upload/download operations
|
|
||||||
- Conflict detection and basic resolution
|
|
||||||
- Network connectivity checking
|
|
||||||
- Device identification
|
|
||||||
|
|
||||||
#### 5. Sync Provider (`lib/providers/sync_provider.dart`)
|
|
||||||
|
|
||||||
State management layer for sync operations:
|
|
||||||
- Manages sync status and progress
|
|
||||||
- Handles user configuration
|
|
||||||
- Coordinates between WebDAV service and UI
|
|
||||||
- Manages conflict resolution workflow
|
|
||||||
|
|
||||||
#### 6. UI Components
|
|
||||||
|
|
||||||
- `SyncSettingsScreen` - Complete WebDAV configuration interface
|
|
||||||
- Integration with existing settings screen
|
|
||||||
- Real-time sync status indicators
|
|
||||||
- Conflict resolution dialogs
|
|
||||||
|
|
||||||
### Database Schema Changes
|
|
||||||
|
|
||||||
The database has been upgraded to version 6 with sync support:
|
|
||||||
|
|
||||||
```sql
|
|
||||||
-- New sync columns added to existing tables
|
|
||||||
ALTER TABLE supplements ADD COLUMN syncId TEXT NOT NULL UNIQUE;
|
|
||||||
ALTER TABLE supplements ADD COLUMN lastModified TEXT NOT NULL;
|
|
||||||
ALTER TABLE supplements ADD COLUMN syncStatus TEXT NOT NULL DEFAULT 'pending';
|
|
||||||
ALTER TABLE supplements ADD COLUMN isDeleted INTEGER NOT NULL DEFAULT 0;
|
|
||||||
|
|
||||||
-- Similar columns added to supplement_intakes table
|
|
||||||
|
|
||||||
-- New sync metadata table
|
|
||||||
CREATE TABLE sync_metadata (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
key TEXT NOT NULL UNIQUE,
|
|
||||||
value TEXT NOT NULL,
|
|
||||||
lastUpdated TEXT NOT NULL
|
|
||||||
);
|
|
||||||
|
|
||||||
-- Device info table for multi-device conflict resolution
|
|
||||||
CREATE TABLE device_info (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
deviceId TEXT NOT NULL UNIQUE,
|
|
||||||
deviceName TEXT NOT NULL,
|
|
||||||
lastSyncTime TEXT,
|
|
||||||
createdAt TEXT NOT NULL
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
## Sync Process Flow
|
|
||||||
|
|
||||||
### 1. Configuration Phase
|
|
||||||
1. User enters WebDAV server URL, username, and password/app password
|
|
||||||
2. System tests connection and validates credentials
|
|
||||||
3. Creates sync directory on server if needed
|
|
||||||
4. Stores encrypted credentials locally using `flutter_secure_storage`
|
|
||||||
|
|
||||||
### 2. Sync Operation
|
|
||||||
1. Check network connectivity
|
|
||||||
2. Download remote sync data (JSON file from WebDAV)
|
|
||||||
3. Compare with local data using timestamps and sync IDs
|
|
||||||
4. Detect conflicts (modification, deletion, creation conflicts)
|
|
||||||
5. Merge data according to conflict resolution strategy
|
|
||||||
6. Upload merged data back to server
|
|
||||||
7. Update local sync status
|
|
||||||
|
|
||||||
### 3. Conflict Resolution
|
|
||||||
- **Last-write-wins**: Prefer most recently modified record
|
|
||||||
- **Prefer Local**: Always keep local changes
|
|
||||||
- **Prefer Remote**: Always keep remote changes
|
|
||||||
- **Manual**: Present conflicts to user for individual resolution
|
|
||||||
|
|
||||||
## Security Considerations
|
|
||||||
|
|
||||||
### Data Protection
|
|
||||||
- Credentials stored using `flutter_secure_storage` with platform encryption
|
|
||||||
- Support for app passwords instead of main account passwords
|
|
||||||
- No sensitive data logged in release builds
|
|
||||||
|
|
||||||
### Network Security
|
|
||||||
- HTTPS enforced for WebDAV connections
|
|
||||||
- Connection testing before storing credentials
|
|
||||||
- Proper error handling for authentication failures
|
|
||||||
|
|
||||||
## Supported WebDAV Servers
|
|
||||||
|
|
||||||
### Tested Compatibility
|
|
||||||
- **Nextcloud** - Full compatibility with automatic path detection
|
|
||||||
- **ownCloud** - Full compatibility with automatic path detection
|
|
||||||
- **Generic WebDAV** - Manual path configuration required
|
|
||||||
|
|
||||||
### Server Requirements
|
|
||||||
- WebDAV protocol support
|
|
||||||
- File read/write permissions
|
|
||||||
- Directory creation permissions
|
|
||||||
- Basic or digest authentication
|
|
||||||
|
|
||||||
## Data Synchronization Format
|
|
||||||
|
|
||||||
### JSON Structure
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"version": 1,
|
|
||||||
"deviceId": "device_12345_67890",
|
|
||||||
"deviceName": "John's Phone",
|
|
||||||
"syncTimestamp": "2024-01-15T10:30:00.000Z",
|
|
||||||
"supplements": [
|
|
||||||
{
|
|
||||||
"syncId": "uuid-supplement-1",
|
|
||||||
"name": "Vitamin D3",
|
|
||||||
"ingredients": [...],
|
|
||||||
"lastModified": "2024-01-15T09:15:00.000Z",
|
|
||||||
"syncStatus": "synced",
|
|
||||||
"isDeleted": false,
|
|
||||||
// ... other supplement fields
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"intakes": [
|
|
||||||
{
|
|
||||||
"syncId": "uuid-intake-1",
|
|
||||||
"supplementId": 1,
|
|
||||||
"takenAt": "2024-01-15T08:00:00.000Z",
|
|
||||||
"lastModified": "2024-01-15T08:00:30.000Z",
|
|
||||||
"syncStatus": "synced",
|
|
||||||
"isDeleted": false,
|
|
||||||
// ... other intake fields
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"totalSupplements": 5,
|
|
||||||
"totalIntakes": 150
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Usage Instructions
|
|
||||||
|
|
||||||
### Initial Setup
|
|
||||||
1. Navigate to Settings → Cloud Sync
|
|
||||||
2. Enter your WebDAV server details:
|
|
||||||
- Server URL (e.g., `https://cloud.example.com`)
|
|
||||||
- Username
|
|
||||||
- Password or app password
|
|
||||||
- Optional device name
|
|
||||||
3. Test connection
|
|
||||||
4. Configure sync preferences
|
|
||||||
|
|
||||||
### Sync Options
|
|
||||||
- **Manual Sync**: Sync on demand via button press
|
|
||||||
- **Auto Sync**: Automatic background sync at configured intervals
|
|
||||||
- Every 15 minutes
|
|
||||||
- Hourly
|
|
||||||
- Every 6 hours
|
|
||||||
- Daily
|
|
||||||
|
|
||||||
### Conflict Resolution
|
|
||||||
- Configure preferred resolution strategy in settings
|
|
||||||
- Review individual conflicts when they occur
|
|
||||||
- Auto-resolve based on chosen strategy
|
|
||||||
|
|
||||||
## Implementation Status
|
|
||||||
|
|
||||||
### ✅ Completed (Phase 1)
|
|
||||||
- Core sync architecture and data models
|
|
||||||
- WebDAV service implementation
|
|
||||||
- Database schema with sync support
|
|
||||||
- Basic UI for configuration and management
|
|
||||||
- Manual sync operations
|
|
||||||
- Conflict detection
|
|
||||||
- Secure credential storage
|
|
||||||
|
|
||||||
### 🔄 Future Enhancements (Phase 2+)
|
|
||||||
- Background sync scheduling
|
|
||||||
- Advanced conflict resolution UI
|
|
||||||
- Sync history and logs
|
|
||||||
- Client-side encryption option
|
|
||||||
- Multiple server support
|
|
||||||
- Bandwidth optimization
|
|
||||||
- Offline queue management
|
|
||||||
|
|
||||||
## Dependencies Added
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
dependencies:
|
|
||||||
webdav_client: ^1.2.2 # WebDAV protocol client
|
|
||||||
connectivity_plus: ^6.0.5 # Network connectivity checking
|
|
||||||
flutter_secure_storage: ^9.2.2 # Secure credential storage
|
|
||||||
uuid: ^4.5.0 # UUID generation for sync IDs
|
|
||||||
crypto: ^3.0.5 # Data integrity verification
|
|
||||||
```
|
|
||||||
|
|
||||||
## File Structure
|
|
||||||
|
|
||||||
```
|
|
||||||
lib/
|
|
||||||
├── models/
|
|
||||||
│ ├── sync_enums.dart # Sync-related enumerations
|
|
||||||
│ ├── sync_data.dart # Sync data models
|
|
||||||
│ ├── supplement.dart # Enhanced with sync metadata
|
|
||||||
│ ├── supplement_intake.dart # Enhanced with sync metadata
|
|
||||||
│ └── ingredient.dart # Enhanced with sync metadata
|
|
||||||
├── services/
|
|
||||||
│ ├── webdav_sync_service.dart # WebDAV communication
|
|
||||||
│ └── database_helper.dart # Enhanced with sync methods
|
|
||||||
├── providers/
|
|
||||||
│ └── sync_provider.dart # Sync state management
|
|
||||||
└── screens/
|
|
||||||
└── sync_settings_screen.dart # Sync configuration UI
|
|
||||||
```
|
|
||||||
|
|
||||||
## Error Handling
|
|
||||||
|
|
||||||
The implementation includes comprehensive error handling for:
|
|
||||||
- Network connectivity issues
|
|
||||||
- Authentication failures
|
|
||||||
- Server unavailability
|
|
||||||
- Malformed sync data
|
|
||||||
- Storage permission issues
|
|
||||||
- Conflicting concurrent modifications
|
|
||||||
|
|
||||||
## Testing Recommendations
|
|
||||||
|
|
||||||
### Unit Tests
|
|
||||||
- Sync data serialization/deserialization
|
|
||||||
- Conflict detection algorithms
|
|
||||||
- Merge logic validation
|
|
||||||
|
|
||||||
### Integration Tests
|
|
||||||
- WebDAV server communication
|
|
||||||
- Database sync operations
|
|
||||||
- Cross-device sync scenarios
|
|
||||||
|
|
||||||
### User Testing
|
|
||||||
- Multi-device sync workflows
|
|
||||||
- Network interruption recovery
|
|
||||||
- Large dataset synchronization
|
|
||||||
- Conflict resolution user experience
|
|
||||||
|
|
||||||
## Performance Considerations
|
|
||||||
|
|
||||||
- Incremental sync (only changed data)
|
|
||||||
- Compression for large datasets
|
|
||||||
- Connection timeout handling
|
|
||||||
- Memory-efficient JSON processing
|
|
||||||
- Background processing for large operations
|
|
||||||
|
|
||||||
This implementation provides a solid foundation for cloud synchronization while maintaining data integrity and user experience across multiple devices.
|
|
||||||
@@ -4,12 +4,20 @@
|
|||||||
<uses-permission android:name="android.permission.VIBRATE" />
|
<uses-permission android:name="android.permission.VIBRATE" />
|
||||||
<uses-permission android:name="android.permission.USE_EXACT_ALARM" />
|
<uses-permission android:name="android.permission.USE_EXACT_ALARM" />
|
||||||
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
|
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
|
||||||
|
<uses-permission android:name="android.permission.WAKE_LOCK"/>
|
||||||
|
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT"/>
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
|
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
|
||||||
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
|
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
|
||||||
|
|
||||||
<application
|
<application
|
||||||
android:label="supplements"
|
android:label="My Supplements"
|
||||||
android:name="${applicationName}"
|
android:name="${applicationName}"
|
||||||
android:icon="@mipmap/ic_launcher"
|
android:icon="@mipmap/ic_launcher"
|
||||||
android:enableOnBackInvokedCallback="true">
|
android:enableOnBackInvokedCallback="true">
|
||||||
|
<service android:name="com.gdelataillade.alarm.services.NotificationOnKillService" />
|
||||||
<activity
|
<activity
|
||||||
android:name=".MainActivity"
|
android:name=".MainActivity"
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
|
|||||||
71
lib/data/rda_data.dart
Normal file
71
lib/data/rda_data.dart
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
// Recommended Daily Allowances (RDA) for common vitamins and minerals.
|
||||||
|
// All values are in milligrams (mg) unless otherwise specified.
|
||||||
|
const Map<String, Map<String, Map<String, double>>> rdaData = {
|
||||||
|
'Vitamin C': {
|
||||||
|
'Male': {
|
||||||
|
'19-70': 90, // mg
|
||||||
|
},
|
||||||
|
'Female': {
|
||||||
|
'19-70': 75, // mg
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'Vitamin D': {
|
||||||
|
'Male': {
|
||||||
|
'19-70': 15, // mcg
|
||||||
|
},
|
||||||
|
'Female': {
|
||||||
|
'19-70': 15, // mcg
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'Vitamin D3': {
|
||||||
|
'Male': {
|
||||||
|
'19-70': 15, // mcg
|
||||||
|
},
|
||||||
|
'Female': {
|
||||||
|
'19-70': 15, // mcg
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'Vitamin K': {
|
||||||
|
'Male': {
|
||||||
|
'19-100': 120, // mcg
|
||||||
|
},
|
||||||
|
'Female': {
|
||||||
|
'19-100': 90, // mcg
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'Vitamin K2': {
|
||||||
|
'Male': {
|
||||||
|
'19-100': 120, // mcg
|
||||||
|
},
|
||||||
|
'Female': {
|
||||||
|
'19-100': 90, // mcg
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'Calcium': {
|
||||||
|
'Male': {
|
||||||
|
'19-50': 1000, // mg
|
||||||
|
'51-70': 1000, // mg
|
||||||
|
},
|
||||||
|
'Female': {
|
||||||
|
'19-50': 1000, // mg
|
||||||
|
'51-70': 1200, // mg
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'Iron': {
|
||||||
|
'Male': {
|
||||||
|
'19-50': 8, // mg
|
||||||
|
},
|
||||||
|
'Female': {
|
||||||
|
'19-50': 18, // mg
|
||||||
|
'51-70': 8, // mg
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'DHA & EPA': {
|
||||||
|
'Male': {
|
||||||
|
'19-100': 250, // mg
|
||||||
|
},
|
||||||
|
'Female': {
|
||||||
|
'19-100': 250, // mg
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
8
lib/logging.dart
Normal file
8
lib/logging.dart
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
// A simple logging function that prints a message to the console if [kDebugMode] is enabled.
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
|
||||||
|
void printLog(String message) {
|
||||||
|
if (kDebugMode) {
|
||||||
|
print('SupplementsLog: $message');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,17 +1,47 @@
|
|||||||
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_local_notifications/flutter_local_notifications.dart'; // Import this
|
||||||
|
import 'package:provider/provider.dart';
|
||||||
|
import 'package:supplements/logging.dart';
|
||||||
|
|
||||||
import 'providers/settings_provider.dart';
|
import 'providers/settings_provider.dart';
|
||||||
|
import 'providers/simple_sync_provider.dart';
|
||||||
import 'providers/supplement_provider.dart';
|
import 'providers/supplement_provider.dart';
|
||||||
import 'providers/sync_provider.dart';
|
|
||||||
import 'screens/home_screen.dart';
|
import 'screens/home_screen.dart';
|
||||||
|
import 'services/notification_router.dart';
|
||||||
|
import 'services/simple_notification_service.dart';
|
||||||
|
|
||||||
void main() {
|
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
|
||||||
runApp(const MyApp());
|
|
||||||
|
// Top-level function to handle notification responses in the background
|
||||||
|
@pragma('vm:entry-point')
|
||||||
|
void notificationTapBackground(NotificationResponse notificationResponse) {
|
||||||
|
// handle action here
|
||||||
|
printLog('Background notification action tapped: ${notificationResponse.actionId}');
|
||||||
|
NotificationRouter.instance.handleNotificationResponse(notificationResponse);
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() async {
|
||||||
|
WidgetsFlutterBinding.ensureInitialized();
|
||||||
|
|
||||||
|
// Initialize SimpleNotificationService early
|
||||||
|
await SimpleNotificationService.instance.initialize(
|
||||||
|
onDidReceiveBackgroundNotificationResponse: notificationTapBackground,
|
||||||
|
);
|
||||||
|
|
||||||
|
final settingsProvider = SettingsProvider();
|
||||||
|
await settingsProvider.initialize();
|
||||||
|
|
||||||
|
runApp(MyApp(settingsProvider: settingsProvider));
|
||||||
}
|
}
|
||||||
|
|
||||||
class MyApp extends StatelessWidget {
|
class MyApp extends StatelessWidget {
|
||||||
const MyApp({super.key});
|
final SettingsProvider settingsProvider;
|
||||||
|
|
||||||
|
const MyApp({super.key, required this.settingsProvider});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
@@ -20,18 +50,53 @@ class MyApp extends StatelessWidget {
|
|||||||
ChangeNotifierProvider(
|
ChangeNotifierProvider(
|
||||||
create: (context) => SupplementProvider()..initialize(),
|
create: (context) => SupplementProvider()..initialize(),
|
||||||
),
|
),
|
||||||
ChangeNotifierProvider(
|
ChangeNotifierProvider.value(
|
||||||
create: (context) => SettingsProvider()..initialize(),
|
value: settingsProvider,
|
||||||
),
|
),
|
||||||
ChangeNotifierProxyProvider<SupplementProvider, SyncProvider>(
|
ChangeNotifierProvider(
|
||||||
create: (context) => SyncProvider(context.read<SupplementProvider>())..initialize(),
|
create: (context) => SimpleSyncProvider(),
|
||||||
update: (context, supplementProvider, syncProvider) =>
|
|
||||||
syncProvider ?? SyncProvider(supplementProvider)..initialize(),
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
child: Consumer<SettingsProvider>(
|
child: Consumer2<SettingsProvider, SimpleSyncProvider>(
|
||||||
builder: (context, settingsProvider, child) {
|
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>();
|
||||||
|
|
||||||
|
// Initialize notification router with the app's navigator
|
||||||
|
// This is done here because navigatorKey is only available after MaterialApp is built
|
||||||
|
NotificationRouter.instance.initialize(navigatorKey);
|
||||||
|
|
||||||
|
// If the app was launched via a notification, route to the proper dialog
|
||||||
|
// This needs to be called after the router is initialized with the navigatorKey
|
||||||
|
SimpleNotificationService.instance.getLaunchDetails().then((details) {
|
||||||
|
NotificationRouter.instance.handleAppLaunchDetails(details);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Set up sync completion callback
|
||||||
|
syncProvider.setOnSyncCompleteCallback(() async {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('Sync completed, refreshing UI data...');
|
||||||
|
}
|
||||||
|
await supplementProvider.loadSupplements();
|
||||||
|
await supplementProvider.loadTodayIntakes();
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('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(
|
return MaterialApp(
|
||||||
|
navigatorKey: navigatorKey,
|
||||||
title: 'Supplements Tracker',
|
title: 'Supplements Tracker',
|
||||||
theme: ThemeData(
|
theme: ThemeData(
|
||||||
colorScheme: ColorScheme.fromSeed(
|
colorScheme: ColorScheme.fromSeed(
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import 'sync_enums.dart';
|
import '../services/database_sync_service.dart';
|
||||||
|
|
||||||
class Ingredient {
|
class Ingredient {
|
||||||
final int? id;
|
final int? id;
|
||||||
@@ -9,7 +9,7 @@ class Ingredient {
|
|||||||
// Sync metadata
|
// Sync metadata
|
||||||
final String syncId;
|
final String syncId;
|
||||||
final DateTime lastModified;
|
final DateTime lastModified;
|
||||||
final SyncStatus syncStatus;
|
final RecordSyncStatus syncStatus;
|
||||||
final bool isDeleted;
|
final bool isDeleted;
|
||||||
|
|
||||||
const Ingredient({
|
const Ingredient({
|
||||||
@@ -19,7 +19,7 @@ class Ingredient {
|
|||||||
required this.unit,
|
required this.unit,
|
||||||
required this.syncId,
|
required this.syncId,
|
||||||
required this.lastModified,
|
required this.lastModified,
|
||||||
this.syncStatus = SyncStatus.pending,
|
this.syncStatus = RecordSyncStatus.pending,
|
||||||
this.isDeleted = false,
|
this.isDeleted = false,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -47,11 +47,11 @@ class Ingredient {
|
|||||||
? DateTime.parse(map['lastModified'])
|
? DateTime.parse(map['lastModified'])
|
||||||
: DateTime.now(),
|
: DateTime.now(),
|
||||||
syncStatus: map['syncStatus'] != null
|
syncStatus: map['syncStatus'] != null
|
||||||
? SyncStatus.values.firstWhere(
|
? RecordSyncStatus.values.firstWhere(
|
||||||
(e) => e.name == map['syncStatus'],
|
(e) => e.name == map['syncStatus'],
|
||||||
orElse: () => SyncStatus.pending,
|
orElse: () => RecordSyncStatus.pending,
|
||||||
)
|
)
|
||||||
: SyncStatus.pending,
|
: RecordSyncStatus.pending,
|
||||||
isDeleted: (map['isDeleted'] ?? 0) == 1,
|
isDeleted: (map['isDeleted'] ?? 0) == 1,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -63,7 +63,7 @@ class Ingredient {
|
|||||||
String? unit,
|
String? unit,
|
||||||
String? syncId,
|
String? syncId,
|
||||||
DateTime? lastModified,
|
DateTime? lastModified,
|
||||||
SyncStatus? syncStatus,
|
RecordSyncStatus? syncStatus,
|
||||||
bool? isDeleted,
|
bool? isDeleted,
|
||||||
}) {
|
}) {
|
||||||
return Ingredient(
|
return Ingredient(
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ import 'dart:convert';
|
|||||||
|
|
||||||
import 'package:uuid/uuid.dart';
|
import 'package:uuid/uuid.dart';
|
||||||
|
|
||||||
|
import '../services/database_sync_service.dart';
|
||||||
import 'ingredient.dart';
|
import 'ingredient.dart';
|
||||||
import 'sync_enums.dart';
|
|
||||||
|
|
||||||
class Supplement {
|
class Supplement {
|
||||||
final int? id;
|
final int? id;
|
||||||
@@ -21,7 +21,7 @@ class Supplement {
|
|||||||
// Sync metadata
|
// Sync metadata
|
||||||
final String syncId;
|
final String syncId;
|
||||||
final DateTime lastModified;
|
final DateTime lastModified;
|
||||||
final SyncStatus syncStatus;
|
final RecordSyncStatus syncStatus;
|
||||||
final bool isDeleted;
|
final bool isDeleted;
|
||||||
|
|
||||||
Supplement({
|
Supplement({
|
||||||
@@ -38,7 +38,7 @@ class Supplement {
|
|||||||
this.isActive = true,
|
this.isActive = true,
|
||||||
String? syncId,
|
String? syncId,
|
||||||
DateTime? lastModified,
|
DateTime? lastModified,
|
||||||
this.syncStatus = SyncStatus.pending,
|
this.syncStatus = RecordSyncStatus.pending,
|
||||||
this.isDeleted = false,
|
this.isDeleted = false,
|
||||||
}) : syncId = syncId ?? const Uuid().v4(),
|
}) : syncId = syncId ?? const Uuid().v4(),
|
||||||
lastModified = lastModified ?? DateTime.now();
|
lastModified = lastModified ?? DateTime.now();
|
||||||
@@ -69,8 +69,7 @@ class Supplement {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Map<String, dynamic> toMap() {
|
Map<String, dynamic> toMap() {
|
||||||
return {
|
final map = <String, dynamic>{
|
||||||
'id': id,
|
|
||||||
'name': name,
|
'name': name,
|
||||||
'brand': brand,
|
'brand': brand,
|
||||||
'ingredients': jsonEncode(ingredients.map((ingredient) => ingredient.toMap()).toList()),
|
'ingredients': jsonEncode(ingredients.map((ingredient) => ingredient.toMap()).toList()),
|
||||||
@@ -86,6 +85,12 @@ class Supplement {
|
|||||||
'syncStatus': syncStatus.name,
|
'syncStatus': syncStatus.name,
|
||||||
'isDeleted': isDeleted ? 1 : 0,
|
'isDeleted': isDeleted ? 1 : 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (id != null) {
|
||||||
|
map['id'] = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
return map;
|
||||||
}
|
}
|
||||||
|
|
||||||
factory Supplement.fromMap(Map<String, dynamic> map) {
|
factory Supplement.fromMap(Map<String, dynamic> map) {
|
||||||
@@ -122,17 +127,18 @@ class Supplement {
|
|||||||
? DateTime.parse(map['lastModified'])
|
? DateTime.parse(map['lastModified'])
|
||||||
: DateTime.now(),
|
: DateTime.now(),
|
||||||
syncStatus: map['syncStatus'] != null
|
syncStatus: map['syncStatus'] != null
|
||||||
? SyncStatus.values.firstWhere(
|
? RecordSyncStatus.values.firstWhere(
|
||||||
(e) => e.name == map['syncStatus'],
|
(e) => e.name == map['syncStatus'],
|
||||||
orElse: () => SyncStatus.pending,
|
orElse: () => RecordSyncStatus.pending,
|
||||||
)
|
)
|
||||||
: SyncStatus.pending,
|
: RecordSyncStatus.pending,
|
||||||
isDeleted: (map['isDeleted'] ?? 0) == 1,
|
isDeleted: (map['isDeleted'] ?? 0) == 1,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Supplement copyWith({
|
Supplement copyWith({
|
||||||
int? id,
|
int? id,
|
||||||
|
bool setNullId = false,
|
||||||
String? name,
|
String? name,
|
||||||
String? brand,
|
String? brand,
|
||||||
List<Ingredient>? ingredients,
|
List<Ingredient>? ingredients,
|
||||||
@@ -144,12 +150,13 @@ class Supplement {
|
|||||||
DateTime? createdAt,
|
DateTime? createdAt,
|
||||||
bool? isActive,
|
bool? isActive,
|
||||||
String? syncId,
|
String? syncId,
|
||||||
|
bool newSyncId = false,
|
||||||
DateTime? lastModified,
|
DateTime? lastModified,
|
||||||
SyncStatus? syncStatus,
|
RecordSyncStatus? syncStatus,
|
||||||
bool? isDeleted,
|
bool? isDeleted,
|
||||||
}) {
|
}) {
|
||||||
return Supplement(
|
return Supplement(
|
||||||
id: id ?? this.id,
|
id: setNullId ? null : (id ?? this.id),
|
||||||
name: name ?? this.name,
|
name: name ?? this.name,
|
||||||
brand: brand ?? this.brand,
|
brand: brand ?? this.brand,
|
||||||
ingredients: ingredients ?? this.ingredients,
|
ingredients: ingredients ?? this.ingredients,
|
||||||
@@ -160,7 +167,7 @@ class Supplement {
|
|||||||
notes: notes ?? this.notes,
|
notes: notes ?? this.notes,
|
||||||
createdAt: createdAt ?? this.createdAt,
|
createdAt: createdAt ?? this.createdAt,
|
||||||
isActive: isActive ?? this.isActive,
|
isActive: isActive ?? this.isActive,
|
||||||
syncId: syncId ?? this.syncId,
|
syncId: newSyncId ? null : (syncId ?? this.syncId),
|
||||||
lastModified: lastModified ?? this.lastModified,
|
lastModified: lastModified ?? this.lastModified,
|
||||||
syncStatus: syncStatus ?? this.syncStatus,
|
syncStatus: syncStatus ?? this.syncStatus,
|
||||||
isDeleted: isDeleted ?? this.isDeleted,
|
isDeleted: isDeleted ?? this.isDeleted,
|
||||||
@@ -171,14 +178,14 @@ class Supplement {
|
|||||||
Supplement markAsModified() {
|
Supplement markAsModified() {
|
||||||
return copyWith(
|
return copyWith(
|
||||||
lastModified: DateTime.now(),
|
lastModified: DateTime.now(),
|
||||||
syncStatus: SyncStatus.modified,
|
syncStatus: RecordSyncStatus.modified,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create a new supplement marked as synced
|
/// Create a new supplement marked as synced
|
||||||
Supplement markAsSynced() {
|
Supplement markAsSynced() {
|
||||||
return copyWith(
|
return copyWith(
|
||||||
syncStatus: SyncStatus.synced,
|
syncStatus: RecordSyncStatus.synced,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -187,7 +194,7 @@ class Supplement {
|
|||||||
return copyWith(
|
return copyWith(
|
||||||
isDeleted: true,
|
isDeleted: true,
|
||||||
lastModified: DateTime.now(),
|
lastModified: DateTime.now(),
|
||||||
syncStatus: SyncStatus.modified,
|
syncStatus: RecordSyncStatus.modified,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import 'package:uuid/uuid.dart';
|
import 'package:uuid/uuid.dart';
|
||||||
|
|
||||||
import 'sync_enums.dart';
|
import '../services/database_sync_service.dart';
|
||||||
|
|
||||||
class SupplementIntake {
|
class SupplementIntake {
|
||||||
final int? id;
|
final int? id;
|
||||||
@@ -13,7 +13,7 @@ class SupplementIntake {
|
|||||||
// Sync metadata
|
// Sync metadata
|
||||||
final String syncId;
|
final String syncId;
|
||||||
final DateTime lastModified;
|
final DateTime lastModified;
|
||||||
final SyncStatus syncStatus;
|
final RecordSyncStatus syncStatus;
|
||||||
final bool isDeleted;
|
final bool isDeleted;
|
||||||
|
|
||||||
SupplementIntake({
|
SupplementIntake({
|
||||||
@@ -25,7 +25,7 @@ class SupplementIntake {
|
|||||||
this.notes,
|
this.notes,
|
||||||
String? syncId,
|
String? syncId,
|
||||||
DateTime? lastModified,
|
DateTime? lastModified,
|
||||||
this.syncStatus = SyncStatus.pending,
|
this.syncStatus = RecordSyncStatus.pending,
|
||||||
this.isDeleted = false,
|
this.isDeleted = false,
|
||||||
}) : syncId = syncId ?? const Uuid().v4(),
|
}) : syncId = syncId ?? const Uuid().v4(),
|
||||||
lastModified = lastModified ?? DateTime.now();
|
lastModified = lastModified ?? DateTime.now();
|
||||||
@@ -58,11 +58,11 @@ class SupplementIntake {
|
|||||||
? DateTime.parse(map['lastModified'])
|
? DateTime.parse(map['lastModified'])
|
||||||
: DateTime.now(),
|
: DateTime.now(),
|
||||||
syncStatus: map['syncStatus'] != null
|
syncStatus: map['syncStatus'] != null
|
||||||
? SyncStatus.values.firstWhere(
|
? RecordSyncStatus.values.firstWhere(
|
||||||
(e) => e.name == map['syncStatus'],
|
(e) => e.name == map['syncStatus'],
|
||||||
orElse: () => SyncStatus.pending,
|
orElse: () => RecordSyncStatus.pending,
|
||||||
)
|
)
|
||||||
: SyncStatus.pending,
|
: RecordSyncStatus.pending,
|
||||||
isDeleted: (map['isDeleted'] ?? 0) == 1,
|
isDeleted: (map['isDeleted'] ?? 0) == 1,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -76,7 +76,7 @@ class SupplementIntake {
|
|||||||
String? notes,
|
String? notes,
|
||||||
String? syncId,
|
String? syncId,
|
||||||
DateTime? lastModified,
|
DateTime? lastModified,
|
||||||
SyncStatus? syncStatus,
|
RecordSyncStatus? syncStatus,
|
||||||
bool? isDeleted,
|
bool? isDeleted,
|
||||||
}) {
|
}) {
|
||||||
return SupplementIntake(
|
return SupplementIntake(
|
||||||
@@ -96,7 +96,7 @@ class SupplementIntake {
|
|||||||
/// Create a new intake marked as synced
|
/// Create a new intake marked as synced
|
||||||
SupplementIntake markAsSynced() {
|
SupplementIntake markAsSynced() {
|
||||||
return copyWith(
|
return copyWith(
|
||||||
syncStatus: SyncStatus.synced,
|
syncStatus: RecordSyncStatus.synced,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,7 +105,7 @@ class SupplementIntake {
|
|||||||
return copyWith(
|
return copyWith(
|
||||||
isDeleted: true,
|
isDeleted: true,
|
||||||
lastModified: DateTime.now(),
|
lastModified: DateTime.now(),
|
||||||
syncStatus: SyncStatus.modified,
|
syncStatus: RecordSyncStatus.modified,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,314 +0,0 @@
|
|||||||
import 'dart:convert';
|
|
||||||
|
|
||||||
import 'supplement.dart';
|
|
||||||
import 'supplement_intake.dart';
|
|
||||||
import 'sync_enums.dart';
|
|
||||||
|
|
||||||
/// Model representing the complete sync data structure
|
|
||||||
/// This is what gets serialized to JSON and synced via WebDAV
|
|
||||||
class SyncData {
|
|
||||||
final int version;
|
|
||||||
final String deviceId;
|
|
||||||
final String deviceName;
|
|
||||||
final DateTime syncTimestamp;
|
|
||||||
final List<Supplement> supplements;
|
|
||||||
final List<SupplementIntake> intakes;
|
|
||||||
final Map<String, dynamic> metadata;
|
|
||||||
|
|
||||||
const SyncData({
|
|
||||||
required this.version,
|
|
||||||
required this.deviceId,
|
|
||||||
required this.deviceName,
|
|
||||||
required this.syncTimestamp,
|
|
||||||
required this.supplements,
|
|
||||||
required this.intakes,
|
|
||||||
this.metadata = const {},
|
|
||||||
});
|
|
||||||
|
|
||||||
/// Convert sync data to JSON map
|
|
||||||
Map<String, dynamic> toJson() {
|
|
||||||
return {
|
|
||||||
'version': version,
|
|
||||||
'deviceId': deviceId,
|
|
||||||
'deviceName': deviceName,
|
|
||||||
'syncTimestamp': syncTimestamp.toIso8601String(),
|
|
||||||
'supplements': supplements.map((s) => s.toMap()).toList(),
|
|
||||||
'intakes': intakes.map((i) => i.toMap()).toList(),
|
|
||||||
'metadata': metadata,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Create sync data from JSON map
|
|
||||||
factory SyncData.fromJson(Map<String, dynamic> json) {
|
|
||||||
return SyncData(
|
|
||||||
version: json['version'] ?? 1,
|
|
||||||
deviceId: json['deviceId'] ?? '',
|
|
||||||
deviceName: json['deviceName'] ?? 'Unknown Device',
|
|
||||||
syncTimestamp: json['syncTimestamp'] != null
|
|
||||||
? DateTime.parse(json['syncTimestamp'])
|
|
||||||
: DateTime.now(),
|
|
||||||
supplements: (json['supplements'] as List<dynamic>? ?? [])
|
|
||||||
.map((s) => Supplement.fromMap(s as Map<String, dynamic>))
|
|
||||||
.toList(),
|
|
||||||
intakes: (json['intakes'] as List<dynamic>? ?? [])
|
|
||||||
.map((i) => SupplementIntake.fromMap(i as Map<String, dynamic>))
|
|
||||||
.toList(),
|
|
||||||
metadata: json['metadata'] as Map<String, dynamic>? ?? {},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Convert sync data to JSON string
|
|
||||||
String toJsonString() {
|
|
||||||
return jsonEncode(toJson());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Create sync data from JSON string
|
|
||||||
factory SyncData.fromJsonString(String jsonString) {
|
|
||||||
final json = jsonDecode(jsonString) as Map<String, dynamic>;
|
|
||||||
return SyncData.fromJson(json);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Create a copy with updated values
|
|
||||||
SyncData copyWith({
|
|
||||||
int? version,
|
|
||||||
String? deviceId,
|
|
||||||
String? deviceName,
|
|
||||||
DateTime? syncTimestamp,
|
|
||||||
List<Supplement>? supplements,
|
|
||||||
List<SupplementIntake>? intakes,
|
|
||||||
Map<String, dynamic>? metadata,
|
|
||||||
}) {
|
|
||||||
return SyncData(
|
|
||||||
version: version ?? this.version,
|
|
||||||
deviceId: deviceId ?? this.deviceId,
|
|
||||||
deviceName: deviceName ?? this.deviceName,
|
|
||||||
syncTimestamp: syncTimestamp ?? this.syncTimestamp,
|
|
||||||
supplements: supplements ?? this.supplements,
|
|
||||||
intakes: intakes ?? this.intakes,
|
|
||||||
metadata: metadata ?? this.metadata,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
String toString() {
|
|
||||||
return 'SyncData(version: $version, deviceId: $deviceId, '
|
|
||||||
'deviceName: $deviceName, syncTimestamp: $syncTimestamp, '
|
|
||||||
'supplements: ${supplements.length}, intakes: ${intakes.length})';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Model representing a sync conflict
|
|
||||||
class SyncConflict {
|
|
||||||
final String syncId;
|
|
||||||
final ConflictType type;
|
|
||||||
final DateTime localTimestamp;
|
|
||||||
final DateTime remoteTimestamp;
|
|
||||||
final Map<String, dynamic> localData;
|
|
||||||
final Map<String, dynamic> remoteData;
|
|
||||||
final ConflictResolutionStrategy? suggestedResolution;
|
|
||||||
|
|
||||||
const SyncConflict({
|
|
||||||
required this.syncId,
|
|
||||||
required this.type,
|
|
||||||
required this.localTimestamp,
|
|
||||||
required this.remoteTimestamp,
|
|
||||||
required this.localData,
|
|
||||||
required this.remoteData,
|
|
||||||
this.suggestedResolution,
|
|
||||||
});
|
|
||||||
|
|
||||||
Map<String, dynamic> toJson() {
|
|
||||||
return {
|
|
||||||
'syncId': syncId,
|
|
||||||
'type': type.name,
|
|
||||||
'localTimestamp': localTimestamp.toIso8601String(),
|
|
||||||
'remoteTimestamp': remoteTimestamp.toIso8601String(),
|
|
||||||
'localData': localData,
|
|
||||||
'remoteData': remoteData,
|
|
||||||
'suggestedResolution': suggestedResolution?.name,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
factory SyncConflict.fromJson(Map<String, dynamic> json) {
|
|
||||||
return SyncConflict(
|
|
||||||
syncId: json['syncId'],
|
|
||||||
type: ConflictType.values.firstWhere(
|
|
||||||
(e) => e.name == json['type'],
|
|
||||||
orElse: () => ConflictType.modification,
|
|
||||||
),
|
|
||||||
localTimestamp: DateTime.parse(json['localTimestamp']),
|
|
||||||
remoteTimestamp: DateTime.parse(json['remoteTimestamp']),
|
|
||||||
localData: json['localData'] as Map<String, dynamic>,
|
|
||||||
remoteData: json['remoteData'] as Map<String, dynamic>,
|
|
||||||
suggestedResolution: json['suggestedResolution'] != null
|
|
||||||
? ConflictResolutionStrategy.values.firstWhere(
|
|
||||||
(e) => e.name == json['suggestedResolution'],
|
|
||||||
orElse: () => ConflictResolutionStrategy.manual,
|
|
||||||
)
|
|
||||||
: null,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get human-readable description of the conflict
|
|
||||||
String get description {
|
|
||||||
switch (type) {
|
|
||||||
case ConflictType.modification:
|
|
||||||
return 'Item modified on both devices';
|
|
||||||
case ConflictType.deletion:
|
|
||||||
return 'Item deleted on one device, modified on another';
|
|
||||||
case ConflictType.creation:
|
|
||||||
return 'Item created with same ID on both devices';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Determine if local version is newer
|
|
||||||
bool get isLocalNewer => localTimestamp.isAfter(remoteTimestamp);
|
|
||||||
|
|
||||||
/// Determine if remote version is newer
|
|
||||||
bool get isRemoteNewer => remoteTimestamp.isAfter(localTimestamp);
|
|
||||||
|
|
||||||
/// Check if timestamps are identical
|
|
||||||
bool get haveSameTimestamp => localTimestamp.isAtSameMomentAs(remoteTimestamp);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Types of sync conflicts
|
|
||||||
enum ConflictType {
|
|
||||||
/// Both local and remote versions were modified
|
|
||||||
modification,
|
|
||||||
|
|
||||||
/// One version was deleted while the other was modified
|
|
||||||
deletion,
|
|
||||||
|
|
||||||
/// Same item was created on both devices
|
|
||||||
creation,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Model for sync operation results
|
|
||||||
class SyncResult {
|
|
||||||
final bool success;
|
|
||||||
final DateTime timestamp;
|
|
||||||
final SyncOperationStatus status;
|
|
||||||
final String? error;
|
|
||||||
final List<SyncConflict> conflicts;
|
|
||||||
final SyncStatistics statistics;
|
|
||||||
|
|
||||||
const SyncResult({
|
|
||||||
required this.success,
|
|
||||||
required this.timestamp,
|
|
||||||
required this.status,
|
|
||||||
this.error,
|
|
||||||
this.conflicts = const [],
|
|
||||||
this.statistics = const SyncStatistics(),
|
|
||||||
});
|
|
||||||
|
|
||||||
Map<String, dynamic> toJson() {
|
|
||||||
return {
|
|
||||||
'success': success,
|
|
||||||
'timestamp': timestamp.toIso8601String(),
|
|
||||||
'status': status.name,
|
|
||||||
'error': error,
|
|
||||||
'conflicts': conflicts.map((c) => c.toJson()).toList(),
|
|
||||||
'statistics': statistics.toJson(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
factory SyncResult.fromJson(Map<String, dynamic> json) {
|
|
||||||
return SyncResult(
|
|
||||||
success: json['success'] ?? false,
|
|
||||||
timestamp: DateTime.parse(json['timestamp']),
|
|
||||||
status: SyncOperationStatus.values.firstWhere(
|
|
||||||
(e) => e.name == json['status'],
|
|
||||||
orElse: () => SyncOperationStatus.idle,
|
|
||||||
),
|
|
||||||
error: json['error'],
|
|
||||||
conflicts: (json['conflicts'] as List<dynamic>? ?? [])
|
|
||||||
.map((c) => SyncConflict.fromJson(c as Map<String, dynamic>))
|
|
||||||
.toList(),
|
|
||||||
statistics: json['statistics'] != null
|
|
||||||
? SyncStatistics.fromJson(json['statistics'] as Map<String, dynamic>)
|
|
||||||
: const SyncStatistics(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Create a failed sync result
|
|
||||||
factory SyncResult.failure({
|
|
||||||
required String error,
|
|
||||||
required SyncOperationStatus status,
|
|
||||||
List<SyncConflict> conflicts = const [],
|
|
||||||
}) {
|
|
||||||
return SyncResult(
|
|
||||||
success: false,
|
|
||||||
timestamp: DateTime.now(),
|
|
||||||
status: status,
|
|
||||||
error: error,
|
|
||||||
conflicts: conflicts,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Create a successful sync result
|
|
||||||
factory SyncResult.success({
|
|
||||||
List<SyncConflict> conflicts = const [],
|
|
||||||
SyncStatistics statistics = const SyncStatistics(),
|
|
||||||
}) {
|
|
||||||
return SyncResult(
|
|
||||||
success: true,
|
|
||||||
timestamp: DateTime.now(),
|
|
||||||
status: conflicts.isEmpty
|
|
||||||
? SyncOperationStatus.success
|
|
||||||
: SyncOperationStatus.conflictsDetected,
|
|
||||||
conflicts: conflicts,
|
|
||||||
statistics: statistics,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Statistics about sync operations
|
|
||||||
class SyncStatistics {
|
|
||||||
final int supplementsUploaded;
|
|
||||||
final int supplementsDownloaded;
|
|
||||||
final int intakesUploaded;
|
|
||||||
final int intakesDownloaded;
|
|
||||||
final int conflictsResolved;
|
|
||||||
final Duration syncDuration;
|
|
||||||
|
|
||||||
const SyncStatistics({
|
|
||||||
this.supplementsUploaded = 0,
|
|
||||||
this.supplementsDownloaded = 0,
|
|
||||||
this.intakesUploaded = 0,
|
|
||||||
this.intakesDownloaded = 0,
|
|
||||||
this.conflictsResolved = 0,
|
|
||||||
this.syncDuration = Duration.zero,
|
|
||||||
});
|
|
||||||
|
|
||||||
Map<String, dynamic> toJson() {
|
|
||||||
return {
|
|
||||||
'supplementsUploaded': supplementsUploaded,
|
|
||||||
'supplementsDownloaded': supplementsDownloaded,
|
|
||||||
'intakesUploaded': intakesUploaded,
|
|
||||||
'intakesDownloaded': intakesDownloaded,
|
|
||||||
'conflictsResolved': conflictsResolved,
|
|
||||||
'syncDurationMs': syncDuration.inMilliseconds,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
factory SyncStatistics.fromJson(Map<String, dynamic> json) {
|
|
||||||
return SyncStatistics(
|
|
||||||
supplementsUploaded: json['supplementsUploaded'] ?? 0,
|
|
||||||
supplementsDownloaded: json['supplementsDownloaded'] ?? 0,
|
|
||||||
intakesUploaded: json['intakesUploaded'] ?? 0,
|
|
||||||
intakesDownloaded: json['intakesDownloaded'] ?? 0,
|
|
||||||
conflictsResolved: json['conflictsResolved'] ?? 0,
|
|
||||||
syncDuration: Duration(milliseconds: json['syncDurationMs'] ?? 0),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
int get totalUploaded => supplementsUploaded + intakesUploaded;
|
|
||||||
int get totalDownloaded => supplementsDownloaded + intakesDownloaded;
|
|
||||||
int get totalSynced => totalUploaded + totalDownloaded;
|
|
||||||
|
|
||||||
@override
|
|
||||||
String toString() {
|
|
||||||
return 'SyncStatistics(uploaded: $totalUploaded, downloaded: $totalDownloaded, '
|
|
||||||
'conflicts: $conflictsResolved, duration: ${syncDuration.inSeconds}s)';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,178 +0,0 @@
|
|||||||
/// Enumeration for sync status of individual records
|
|
||||||
enum SyncStatus {
|
|
||||||
/// Record is newly created and needs to be synced
|
|
||||||
pending,
|
|
||||||
|
|
||||||
/// Record is in sync with remote server
|
|
||||||
synced,
|
|
||||||
|
|
||||||
/// Record has been modified locally and needs to be synced
|
|
||||||
modified,
|
|
||||||
|
|
||||||
/// Record has a conflict that needs resolution
|
|
||||||
conflict,
|
|
||||||
|
|
||||||
/// Record is being synced (temporary state)
|
|
||||||
syncing,
|
|
||||||
|
|
||||||
/// Record sync failed and will be retried
|
|
||||||
failed,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Enumeration for overall sync operation status
|
|
||||||
enum SyncOperationStatus {
|
|
||||||
/// No sync operation in progress
|
|
||||||
idle,
|
|
||||||
|
|
||||||
/// Currently syncing data
|
|
||||||
syncing,
|
|
||||||
|
|
||||||
/// Last sync completed successfully
|
|
||||||
success,
|
|
||||||
|
|
||||||
/// Last sync failed due to network issues
|
|
||||||
networkError,
|
|
||||||
|
|
||||||
/// Last sync failed due to authentication issues
|
|
||||||
authenticationError,
|
|
||||||
|
|
||||||
/// Last sync failed due to server issues
|
|
||||||
serverError,
|
|
||||||
|
|
||||||
/// Last sync had conflicts that need resolution
|
|
||||||
conflictsDetected,
|
|
||||||
|
|
||||||
/// Sync cancelled by user
|
|
||||||
cancelled,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Enumeration for conflict resolution strategies
|
|
||||||
enum ConflictResolutionStrategy {
|
|
||||||
/// Always prefer local changes
|
|
||||||
preferLocal,
|
|
||||||
|
|
||||||
/// Always prefer remote changes
|
|
||||||
preferRemote,
|
|
||||||
|
|
||||||
/// Prefer the most recently modified record
|
|
||||||
preferNewer,
|
|
||||||
|
|
||||||
/// Ask user to resolve conflicts manually
|
|
||||||
manual,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Enumeration for sync frequency options
|
|
||||||
enum SyncFrequency {
|
|
||||||
/// Manual sync only
|
|
||||||
manual,
|
|
||||||
|
|
||||||
/// Sync every 15 minutes
|
|
||||||
every15Minutes,
|
|
||||||
|
|
||||||
/// Sync every hour
|
|
||||||
hourly,
|
|
||||||
|
|
||||||
/// Sync every 6 hours
|
|
||||||
every6Hours,
|
|
||||||
|
|
||||||
/// Sync once per day
|
|
||||||
daily,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Extension to get human-readable names for SyncStatus
|
|
||||||
extension SyncStatusExtension on SyncStatus {
|
|
||||||
String get displayName {
|
|
||||||
switch (this) {
|
|
||||||
case SyncStatus.pending:
|
|
||||||
return 'Pending Sync';
|
|
||||||
case SyncStatus.synced:
|
|
||||||
return 'Synced';
|
|
||||||
case SyncStatus.modified:
|
|
||||||
return 'Modified';
|
|
||||||
case SyncStatus.conflict:
|
|
||||||
return 'Conflict';
|
|
||||||
case SyncStatus.syncing:
|
|
||||||
return 'Syncing...';
|
|
||||||
case SyncStatus.failed:
|
|
||||||
return 'Sync Failed';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Extension to get human-readable names for SyncOperationStatus
|
|
||||||
extension SyncOperationStatusExtension on SyncOperationStatus {
|
|
||||||
String get displayName {
|
|
||||||
switch (this) {
|
|
||||||
case SyncOperationStatus.idle:
|
|
||||||
return 'Ready';
|
|
||||||
case SyncOperationStatus.syncing:
|
|
||||||
return 'Syncing...';
|
|
||||||
case SyncOperationStatus.success:
|
|
||||||
return 'Sync Complete';
|
|
||||||
case SyncOperationStatus.networkError:
|
|
||||||
return 'Network Error';
|
|
||||||
case SyncOperationStatus.authenticationError:
|
|
||||||
return 'Authentication Failed';
|
|
||||||
case SyncOperationStatus.serverError:
|
|
||||||
return 'Server Error';
|
|
||||||
case SyncOperationStatus.conflictsDetected:
|
|
||||||
return 'Conflicts Detected';
|
|
||||||
case SyncOperationStatus.cancelled:
|
|
||||||
return 'Sync Cancelled';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Extension to get duration for SyncFrequency
|
|
||||||
extension SyncFrequencyExtension on SyncFrequency {
|
|
||||||
Duration get duration {
|
|
||||||
switch (this) {
|
|
||||||
case SyncFrequency.manual:
|
|
||||||
return Duration.zero; // Manual sync only
|
|
||||||
case SyncFrequency.every15Minutes:
|
|
||||||
return const Duration(minutes: 15);
|
|
||||||
case SyncFrequency.hourly:
|
|
||||||
return const Duration(hours: 1);
|
|
||||||
case SyncFrequency.every6Hours:
|
|
||||||
return const Duration(hours: 6);
|
|
||||||
case SyncFrequency.daily:
|
|
||||||
return const Duration(days: 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String get displayName {
|
|
||||||
switch (this) {
|
|
||||||
case SyncFrequency.manual:
|
|
||||||
return 'Manual Only';
|
|
||||||
case SyncFrequency.every15Minutes:
|
|
||||||
return 'Every 15 Minutes';
|
|
||||||
case SyncFrequency.hourly:
|
|
||||||
return 'Hourly';
|
|
||||||
case SyncFrequency.every6Hours:
|
|
||||||
return 'Every 6 Hours';
|
|
||||||
case SyncFrequency.daily:
|
|
||||||
return 'Daily';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Constants for sync operations
|
|
||||||
class SyncConstants {
|
|
||||||
static const String syncFileName = 'supplements_sync.json';
|
|
||||||
static const String syncFileBackupName = 'supplements_sync_backup.json';
|
|
||||||
static const int currentSyncVersion = 1;
|
|
||||||
static const int maxRetryAttempts = 3;
|
|
||||||
static const Duration networkTimeout = Duration(seconds: 30);
|
|
||||||
static const Duration conflictResolutionTimeout = Duration(minutes: 5);
|
|
||||||
|
|
||||||
/// Default WebDAV paths for different cloud providers
|
|
||||||
static const String nextcloudWebdavPath = '/remote.php/dav/files/';
|
|
||||||
static const String owncloudWebdavPath = '/remote.php/webdav/';
|
|
||||||
|
|
||||||
/// Supported cloud providers
|
|
||||||
static const List<String> supportedProviders = [
|
|
||||||
'Nextcloud',
|
|
||||||
'ownCloud',
|
|
||||||
'Generic WebDAV',
|
|
||||||
];
|
|
||||||
}
|
|
||||||
@@ -10,6 +10,10 @@ enum ThemeOption {
|
|||||||
class SettingsProvider extends ChangeNotifier {
|
class SettingsProvider extends ChangeNotifier {
|
||||||
ThemeOption _themeOption = ThemeOption.system;
|
ThemeOption _themeOption = ThemeOption.system;
|
||||||
|
|
||||||
|
// Profile fields
|
||||||
|
DateTime? _dateOfBirth;
|
||||||
|
String? _gender;
|
||||||
|
|
||||||
// Time range settings (stored as hours, 0-23)
|
// Time range settings (stored as hours, 0-23)
|
||||||
int _morningStart = 5;
|
int _morningStart = 5;
|
||||||
int _morningEnd = 10;
|
int _morningEnd = 10;
|
||||||
@@ -20,10 +24,12 @@ class SettingsProvider extends ChangeNotifier {
|
|||||||
int _nightStart = 23;
|
int _nightStart = 23;
|
||||||
int _nightEnd = 4;
|
int _nightEnd = 4;
|
||||||
|
|
||||||
// Persistent reminder settings
|
// Notifications
|
||||||
bool _persistentReminders = true;
|
int _snoozeMinutes = 10;
|
||||||
int _reminderRetryInterval = 5; // minutes
|
|
||||||
int _maxRetryAttempts = 3;
|
// Auto-sync settings
|
||||||
|
bool _autoSyncEnabled = false;
|
||||||
|
int _autoSyncDebounceSeconds = 5;
|
||||||
|
|
||||||
ThemeOption get themeOption => _themeOption;
|
ThemeOption get themeOption => _themeOption;
|
||||||
|
|
||||||
@@ -37,10 +43,12 @@ class SettingsProvider extends ChangeNotifier {
|
|||||||
int get nightStart => _nightStart;
|
int get nightStart => _nightStart;
|
||||||
int get nightEnd => _nightEnd;
|
int get nightEnd => _nightEnd;
|
||||||
|
|
||||||
// Persistent reminder getters
|
// Notifications
|
||||||
bool get persistentReminders => _persistentReminders;
|
int get snoozeMinutes => _snoozeMinutes;
|
||||||
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
|
// Helper method to get formatted time ranges for display
|
||||||
String get morningRange => '${_formatHour(_morningStart)} - ${_formatHour((_morningEnd + 1) % 24)}';
|
String get morningRange => '${_formatHour(_morningStart)} - ${_formatHour((_morningEnd + 1) % 24)}';
|
||||||
@@ -68,6 +76,13 @@ class SettingsProvider extends ChangeNotifier {
|
|||||||
final themeIndex = prefs.getInt('theme_option') ?? 0;
|
final themeIndex = prefs.getInt('theme_option') ?? 0;
|
||||||
_themeOption = ThemeOption.values[themeIndex];
|
_themeOption = ThemeOption.values[themeIndex];
|
||||||
|
|
||||||
|
// Load profile fields
|
||||||
|
final dobString = prefs.getString('date_of_birth');
|
||||||
|
if (dobString != null) {
|
||||||
|
_dateOfBirth = DateTime.tryParse(dobString);
|
||||||
|
}
|
||||||
|
_gender = prefs.getString('gender');
|
||||||
|
|
||||||
// Load time range settings
|
// Load time range settings
|
||||||
_morningStart = prefs.getInt('morning_start') ?? 5;
|
_morningStart = prefs.getInt('morning_start') ?? 5;
|
||||||
_morningEnd = prefs.getInt('morning_end') ?? 10;
|
_morningEnd = prefs.getInt('morning_end') ?? 10;
|
||||||
@@ -78,10 +93,12 @@ class SettingsProvider extends ChangeNotifier {
|
|||||||
_nightStart = prefs.getInt('night_start') ?? 23;
|
_nightStart = prefs.getInt('night_start') ?? 23;
|
||||||
_nightEnd = prefs.getInt('night_end') ?? 4;
|
_nightEnd = prefs.getInt('night_end') ?? 4;
|
||||||
|
|
||||||
// Load persistent reminder settings
|
// Load snooze setting
|
||||||
_persistentReminders = prefs.getBool('persistent_reminders') ?? true;
|
_snoozeMinutes = prefs.getInt('snooze_minutes') ?? 10;
|
||||||
_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();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
@@ -94,6 +111,16 @@ class SettingsProvider extends ChangeNotifier {
|
|||||||
await prefs.setInt('theme_option', option.index);
|
await prefs.setInt('theme_option', option.index);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> setDateOfBirthAndGender(DateTime dateOfBirth, String gender) async {
|
||||||
|
_dateOfBirth = dateOfBirth;
|
||||||
|
_gender = gender;
|
||||||
|
notifyListeners();
|
||||||
|
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setString('date_of_birth', dateOfBirth.toIso8601String());
|
||||||
|
await prefs.setString('gender', gender);
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> setTimeRanges({
|
Future<void> setTimeRanges({
|
||||||
required int morningStart,
|
required int morningStart,
|
||||||
required int morningEnd,
|
required int morningEnd,
|
||||||
@@ -232,28 +259,33 @@ class SettingsProvider extends ChangeNotifier {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Persistent reminder setters
|
// Notifications setters
|
||||||
Future<void> setPersistentReminders(bool enabled) async {
|
Future<void> setSnoozeMinutes(int minutes) async {
|
||||||
_persistentReminders = enabled;
|
const allowed = [5, 10, 15, 20];
|
||||||
|
if (!allowed.contains(minutes)) {
|
||||||
|
throw ArgumentError('Snooze minutes must be one of ${allowed.join(", ")}');
|
||||||
|
}
|
||||||
|
_snoozeMinutes = minutes;
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
|
|
||||||
final prefs = await SharedPreferences.getInstance();
|
final prefs = await SharedPreferences.getInstance();
|
||||||
await prefs.setBool('persistent_reminders', enabled);
|
await prefs.setInt('snooze_minutes', minutes);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> setReminderRetryInterval(int minutes) async {
|
// Auto-sync setters
|
||||||
_reminderRetryInterval = minutes;
|
Future<void> setAutoSyncEnabled(bool enabled) async {
|
||||||
|
_autoSyncEnabled = enabled;
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
|
|
||||||
final prefs = await SharedPreferences.getInstance();
|
final prefs = await SharedPreferences.getInstance();
|
||||||
await prefs.setInt('reminder_retry_interval', minutes);
|
await prefs.setBool('auto_sync_enabled', enabled);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> setMaxRetryAttempts(int attempts) async {
|
Future<void> setAutoSyncDebounceSeconds(int seconds) async {
|
||||||
_maxRetryAttempts = attempts;
|
_autoSyncDebounceSeconds = seconds;
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
|
|
||||||
final prefs = await SharedPreferences.getInstance();
|
final prefs = await SharedPreferences.getInstance();
|
||||||
await prefs.setInt('max_retry_attempts', attempts);
|
await prefs.setInt('auto_sync_debounce_seconds', seconds);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
171
lib/providers/simple_sync_provider.dart
Normal file
171
lib/providers/simple_sync_provider.dart
Normal file
@@ -0,0 +1,171 @@
|
|||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:supplements/logging.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();
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
DateTime? get lastSyncTime => _syncService.lastSyncTime;
|
||||||
|
bool get isConfigured => _syncService.isConfigured;
|
||||||
|
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;
|
||||||
|
String? get username => _syncService.username;
|
||||||
|
String? get password => _syncService.password;
|
||||||
|
String? get remotePath => _syncService.remotePath;
|
||||||
|
|
||||||
|
SimpleSyncProvider() {
|
||||||
|
// Set up callbacks to notify listeners
|
||||||
|
_syncService.onStatusChanged = (_) => notifyListeners();
|
||||||
|
_syncService.onError = (_) => notifyListeners();
|
||||||
|
_syncService.onSyncCompleted = () {
|
||||||
|
notifyListeners();
|
||||||
|
// Trigger UI refresh callback if set
|
||||||
|
_onSyncCompleteCallback?.call();
|
||||||
|
};
|
||||||
|
|
||||||
|
// Load saved configuration and notify listeners when done
|
||||||
|
_loadConfiguration();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set callback to refresh UI data after sync completes
|
||||||
|
void setOnSyncCompleteCallback(VoidCallback? callback) {
|
||||||
|
_onSyncCompleteCallback = callback;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Initialize auto-sync service with settings provider
|
||||||
|
void initializeAutoSync(SettingsProvider settingsProvider) {
|
||||||
|
_autoSyncService = AutoSyncService(
|
||||||
|
syncProvider: this,
|
||||||
|
settingsProvider: settingsProvider,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('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
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> configure({
|
||||||
|
required String serverUrl,
|
||||||
|
required String username,
|
||||||
|
required String password,
|
||||||
|
required String remotePath,
|
||||||
|
}) async {
|
||||||
|
_syncService.configure(
|
||||||
|
serverUrl: serverUrl,
|
||||||
|
username: username,
|
||||||
|
password: password,
|
||||||
|
remotePath: remotePath,
|
||||||
|
);
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<bool> testConnection() async {
|
||||||
|
return await _syncService.testConnection();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> syncDatabase({bool isAutoSync = false}) async {
|
||||||
|
if (!isConfigured) {
|
||||||
|
throw Exception('Sync not configured');
|
||||||
|
}
|
||||||
|
|
||||||
|
_isAutoSync = isAutoSync;
|
||||||
|
notifyListeners();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await _syncService.syncDatabase();
|
||||||
|
} catch (e) {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('Sync failed in provider: $e');
|
||||||
|
}
|
||||||
|
rethrow;
|
||||||
|
} finally {
|
||||||
|
_isAutoSync = false;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void clearError() {
|
||||||
|
_syncService.clearError();
|
||||||
|
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 '$syncType: Downloading remote database...';
|
||||||
|
case SyncStatus.merging:
|
||||||
|
return '$syncType: Merging databases...';
|
||||||
|
case SyncStatus.uploading:
|
||||||
|
return '$syncType: Uploading database...';
|
||||||
|
case SyncStatus.completed:
|
||||||
|
return '$syncType completed successfully';
|
||||||
|
case SyncStatus.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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,21 +3,24 @@ import 'dart:async';
|
|||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:flutter/widgets.dart';
|
import 'package:flutter/widgets.dart';
|
||||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||||
|
import 'package:supplements/logging.dart';
|
||||||
|
|
||||||
import '../models/supplement.dart';
|
import '../models/supplement.dart';
|
||||||
import '../models/supplement_intake.dart';
|
import '../models/supplement_intake.dart';
|
||||||
import '../services/database_helper.dart';
|
import '../services/database_helper.dart';
|
||||||
import '../services/notification_service.dart';
|
import '../services/database_sync_service.dart';
|
||||||
|
import '../services/simple_notification_service.dart';
|
||||||
|
|
||||||
class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
||||||
final DatabaseHelper _databaseHelper = DatabaseHelper.instance;
|
final DatabaseHelper _databaseHelper = DatabaseHelper.instance;
|
||||||
final NotificationService _notificationService = NotificationService();
|
final SimpleNotificationService _notificationService = SimpleNotificationService.instance;
|
||||||
|
bool _initialized = false;
|
||||||
|
|
||||||
List<Supplement> _supplements = [];
|
List<Supplement> _supplements = [];
|
||||||
List<Map<String, dynamic>> _todayIntakes = [];
|
List<Map<String, dynamic>> _todayIntakes = [];
|
||||||
List<Map<String, dynamic>> _monthlyIntakes = [];
|
List<Map<String, dynamic>> _monthlyIntakes = [];
|
||||||
bool _isLoading = false;
|
bool _isLoading = false;
|
||||||
Timer? _persistentReminderTimer;
|
|
||||||
Timer? _dateChangeTimer;
|
Timer? _dateChangeTimer;
|
||||||
DateTime _lastDateCheck = DateTime.now();
|
DateTime _lastDateCheck = DateTime.now();
|
||||||
|
|
||||||
@@ -40,37 +43,22 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> initialize() async {
|
Future<void> initialize() async {
|
||||||
|
if (_initialized) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_initialized = true;
|
||||||
|
|
||||||
// Add this provider as an observer for app lifecycle changes
|
// Add this provider as an observer for app lifecycle changes
|
||||||
WidgetsBinding.instance.addObserver(this);
|
WidgetsBinding.instance.addObserver(this);
|
||||||
|
|
||||||
await _notificationService.initialize();
|
await _notificationService.initialize();
|
||||||
|
|
||||||
// Set up the callback for handling supplement intake from notifications
|
|
||||||
print('📱 Setting up notification callback...');
|
|
||||||
_notificationService.setTakeSupplementCallback((supplementId, supplementName, units, unitType) {
|
|
||||||
print('📱 === NOTIFICATION CALLBACK TRIGGERED ===');
|
|
||||||
print('📱 Supplement ID: $supplementId');
|
|
||||||
print('📱 Supplement Name: $supplementName');
|
|
||||||
print('📱 Units: $units');
|
|
||||||
print('📱 Unit Type: $unitType');
|
|
||||||
|
|
||||||
// Record the intake when user taps "Take" on notification
|
|
||||||
recordIntake(supplementId, 0.0, unitsTaken: units);
|
|
||||||
print('📱 Intake recorded successfully');
|
|
||||||
print('📱 === CALLBACK COMPLETE ===');
|
|
||||||
|
|
||||||
if (kDebugMode) {
|
|
||||||
print('📱 Recorded intake from notification: $supplementName ($units $unitType)');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
print('📱 Notification callback setup complete');
|
|
||||||
|
|
||||||
// Request permissions with error handling
|
// Request permissions with error handling
|
||||||
try {
|
try {
|
||||||
await _notificationService.requestPermissions();
|
await _notificationService.requestPermissions();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('Error requesting notification permissions: $e');
|
printLog('Error requesting notification permissions: $e');
|
||||||
}
|
}
|
||||||
// Continue without notifications rather than crashing
|
// Continue without notifications rather than crashing
|
||||||
}
|
}
|
||||||
@@ -78,35 +66,14 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
await loadSupplements();
|
await loadSupplements();
|
||||||
await loadTodayIntakes();
|
await loadTodayIntakes();
|
||||||
|
|
||||||
// Reschedule notifications for all active supplements to ensure persistence
|
// Schedule notifications for all active supplements
|
||||||
await _rescheduleAllNotifications();
|
await _rescheduleAllNotifications();
|
||||||
|
|
||||||
// Start periodic checking for persistent reminders (every 5 minutes)
|
|
||||||
_startPersistentReminderCheck();
|
|
||||||
|
|
||||||
// Start date change monitoring to reset daily intake status
|
// Start date change monitoring to reset daily intake status
|
||||||
_startDateChangeMonitoring();
|
_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('Error checking persistent reminders: $e');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Also check immediately
|
|
||||||
_checkPersistentReminders();
|
|
||||||
}
|
|
||||||
|
|
||||||
void _startDateChangeMonitoring() {
|
void _startDateChangeMonitoring() {
|
||||||
// Cancel any existing timer
|
// Cancel any existing timer
|
||||||
@@ -120,8 +87,8 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
|
|
||||||
if (currentDate != lastCheckDate) {
|
if (currentDate != lastCheckDate) {
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('Date changed detected: ${lastCheckDate} -> ${currentDate}');
|
printLog('Date changed detected: ${lastCheckDate} -> ${currentDate}');
|
||||||
print('Refreshing today\'s intakes for new day...');
|
printLog('Refreshing today\'s intakes for new day...');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Date has changed, refresh today's intakes
|
// Date has changed, refresh today's intakes
|
||||||
@@ -129,49 +96,22 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
await loadTodayIntakes();
|
await loadTodayIntakes();
|
||||||
|
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('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('📱 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('📱 🔄 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('📱 🚨 MANUAL TRIGGER: Forcing retry check...');
|
|
||||||
await checkPersistentRemindersWithSettings(
|
|
||||||
persistentReminders: true,
|
|
||||||
reminderRetryInterval: 5, // Force 5 minute interval for testing
|
|
||||||
maxRetryAttempts: 3,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
WidgetsBinding.instance.removeObserver(this);
|
WidgetsBinding.instance.removeObserver(this);
|
||||||
_persistentReminderTimer?.cancel();
|
|
||||||
_dateChangeTimer?.cancel();
|
_dateChangeTimer?.cancel();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
@@ -183,7 +123,7 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
if (state == AppLifecycleState.resumed) {
|
if (state == AppLifecycleState.resumed) {
|
||||||
// App came back to foreground, check if date changed
|
// App came back to foreground, check if date changed
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('App resumed, checking for date change...');
|
printLog('App resumed, checking for date change...');
|
||||||
}
|
}
|
||||||
forceCheckDateChange();
|
forceCheckDateChange();
|
||||||
}
|
}
|
||||||
@@ -191,23 +131,20 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
|
|
||||||
Future<void> _rescheduleAllNotifications() async {
|
Future<void> _rescheduleAllNotifications() async {
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('📱 Rescheduling notifications for all active supplements...');
|
printLog('📱 Rescheduling notifications for all active supplements...');
|
||||||
}
|
}
|
||||||
|
|
||||||
for (final supplement in _supplements) {
|
|
||||||
if (supplement.reminderTimes.isNotEmpty) {
|
|
||||||
try {
|
try {
|
||||||
await _notificationService.scheduleSupplementReminders(supplement);
|
await _notificationService.scheduleDailyGroupedRemindersSafe(_supplements);
|
||||||
|
await _notificationService.getPendingNotifications();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('📱 Error rescheduling notifications for ${supplement.name}: $e');
|
printLog('📱 Error scheduling grouped notifications: $e');
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('📱 Finished rescheduling notifications');
|
printLog('📱 Finished rescheduling notifications');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -216,16 +153,16 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
notifyListeners();
|
notifyListeners();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
print('Loading supplements from database...');
|
printLog('Loading supplements from database...');
|
||||||
_supplements = await _databaseHelper.getAllSupplements();
|
_supplements = await _databaseHelper.getAllSupplements();
|
||||||
print('Loaded ${_supplements.length} supplements');
|
printLog('Loaded ${_supplements.length} supplements');
|
||||||
for (var supplement in _supplements) {
|
for (var supplement in _supplements) {
|
||||||
print('Supplement: ${supplement.name}');
|
printLog('Supplement: ${supplement.name}');
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
print('Error loading supplements: $e');
|
printLog('Error loading supplements: $e');
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('Error loading supplements: $e');
|
printLog('Error loading supplements: $e');
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
_isLoading = false;
|
_isLoading = false;
|
||||||
@@ -235,28 +172,23 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
|
|
||||||
Future<void> addSupplement(Supplement supplement) async {
|
Future<void> addSupplement(Supplement supplement) async {
|
||||||
try {
|
try {
|
||||||
print('Adding supplement: ${supplement.name}');
|
printLog('Adding supplement: ${supplement.name}');
|
||||||
final id = await _databaseHelper.insertSupplement(supplement);
|
final id = await _databaseHelper.insertSupplement(supplement);
|
||||||
print('Supplement inserted with ID: $id');
|
printLog('Supplement inserted with ID: $id');
|
||||||
final newSupplement = supplement.copyWith(id: id);
|
final newSupplement = supplement.copyWith(id: id);
|
||||||
|
|
||||||
// Schedule notifications (skip if there's an error)
|
// Notifications will be rescheduled in grouped mode after reloading supplements
|
||||||
try {
|
|
||||||
await _notificationService.scheduleSupplementReminders(newSupplement);
|
|
||||||
print('Notifications scheduled');
|
|
||||||
} catch (notificationError) {
|
|
||||||
print('Warning: Could not schedule notifications: $notificationError');
|
|
||||||
}
|
|
||||||
|
|
||||||
await loadSupplements();
|
await loadSupplements();
|
||||||
print('Supplements reloaded, count: ${_supplements.length}');
|
printLog('Supplements reloaded, count: ${_supplements.length}');
|
||||||
|
await _rescheduleAllNotifications();
|
||||||
|
|
||||||
// Trigger sync after adding supplement
|
// Trigger sync after adding supplement
|
||||||
_triggerSyncIfEnabled();
|
_triggerSyncIfEnabled();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
print('Error adding supplement: $e');
|
printLog('Error adding supplement: $e');
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('Error adding supplement: $e');
|
printLog('Error adding supplement: $e');
|
||||||
}
|
}
|
||||||
rethrow;
|
rethrow;
|
||||||
}
|
}
|
||||||
@@ -266,16 +198,36 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
try {
|
try {
|
||||||
await _databaseHelper.updateSupplement(supplement);
|
await _databaseHelper.updateSupplement(supplement);
|
||||||
|
|
||||||
// Reschedule notifications
|
|
||||||
await _notificationService.scheduleSupplementReminders(supplement);
|
|
||||||
|
|
||||||
await loadSupplements();
|
await loadSupplements();
|
||||||
|
await _rescheduleAllNotifications();
|
||||||
|
|
||||||
// Trigger sync after updating supplement
|
// Trigger sync after updating supplement
|
||||||
_triggerSyncIfEnabled();
|
_triggerSyncIfEnabled();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('Error updating supplement: $e');
|
printLog('Error updating supplement: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> duplicateSupplement(int supplementId) async {
|
||||||
|
try {
|
||||||
|
final originalSupplement = await _databaseHelper.getSupplement(supplementId);
|
||||||
|
if (originalSupplement != null) {
|
||||||
|
final newSupplement = originalSupplement.copyWith(
|
||||||
|
setNullId: true, // This will be a new entry
|
||||||
|
newSyncId: true, // Generate a new syncId
|
||||||
|
name: '${originalSupplement.name} (Copy)',
|
||||||
|
createdAt: DateTime.now(),
|
||||||
|
lastModified: DateTime.now(),
|
||||||
|
syncStatus: RecordSyncStatus.pending,
|
||||||
|
isDeleted: false,
|
||||||
|
);
|
||||||
|
await addSupplement(newSupplement);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('Error duplicating supplement: $e');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -284,16 +236,14 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
try {
|
try {
|
||||||
await _databaseHelper.deleteSupplement(id);
|
await _databaseHelper.deleteSupplement(id);
|
||||||
|
|
||||||
// Cancel notifications
|
|
||||||
await _notificationService.cancelSupplementReminders(id);
|
|
||||||
|
|
||||||
await loadSupplements();
|
await loadSupplements();
|
||||||
|
await _rescheduleAllNotifications();
|
||||||
|
|
||||||
// Trigger sync after deleting supplement
|
// Trigger sync after deleting supplement
|
||||||
_triggerSyncIfEnabled();
|
_triggerSyncIfEnabled();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('Error deleting supplement: $e');
|
printLog('Error deleting supplement: $e');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -317,13 +267,13 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
// Show confirmation notification
|
// Show confirmation notification
|
||||||
final supplement = _supplements.firstWhere((s) => s.id == supplementId);
|
final supplement = _supplements.firstWhere((s) => s.id == supplementId);
|
||||||
final unitsText = unitsTaken != null && unitsTaken != 1 ? '${unitsTaken.toStringAsFixed(unitsTaken % 1 == 0 ? 0 : 1)} ${supplement.unitType}' : '';
|
final unitsText = unitsTaken != null && unitsTaken != 1 ? '${unitsTaken.toStringAsFixed(unitsTaken % 1 == 0 ? 0 : 1)} ${supplement.unitType}' : '';
|
||||||
await _notificationService.showInstantNotification(
|
await _notificationService.showInstant(
|
||||||
'Supplement Taken',
|
title: 'Supplement Taken',
|
||||||
'Recorded ${supplement.name}${unitsText.isNotEmpty ? ' - $unitsText' : ''} (${supplement.ingredientsDisplay})',
|
body: 'Recorded ${supplement.name}${unitsText.isNotEmpty ? ' - $unitsText' : ''} (${supplement.ingredientsDisplay})',
|
||||||
);
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('Error recording intake: $e');
|
printLog('Error recording intake: $e');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -332,22 +282,22 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
try {
|
try {
|
||||||
final today = DateTime.now();
|
final today = DateTime.now();
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('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);
|
_todayIntakes = await _databaseHelper.getIntakesWithSupplementsForDate(today);
|
||||||
|
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('Loaded ${_todayIntakes.length} intakes for today');
|
printLog('Loaded ${_todayIntakes.length} intakes for today');
|
||||||
for (var intake in _todayIntakes) {
|
for (var intake in _todayIntakes) {
|
||||||
print(' - Supplement ID: ${intake['supplement_id']}, taken at: ${intake['takenAt']}');
|
printLog(' - Supplement ID: ${intake['supplement_id']}, taken at: ${intake['takenAt']}');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('Error loading today\'s intakes: $e');
|
printLog('Error loading today\'s intakes: $e');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -358,7 +308,7 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
notifyListeners();
|
notifyListeners();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('Error loading monthly intakes: $e');
|
printLog('Error loading monthly intakes: $e');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -368,7 +318,7 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
return await _databaseHelper.getIntakesWithSupplementsForDate(date);
|
return await _databaseHelper.getIntakesWithSupplementsForDate(date);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('Error loading intakes for date: $e');
|
printLog('Error loading intakes for date: $e');
|
||||||
}
|
}
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
@@ -388,7 +338,26 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
_triggerSyncIfEnabled();
|
_triggerSyncIfEnabled();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('Error deleting intake: $e');
|
printLog('Error deleting intake: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> permanentlyDeleteIntake(int intakeId) async {
|
||||||
|
try {
|
||||||
|
await _databaseHelper.permanentlyDeleteIntake(intakeId);
|
||||||
|
await loadTodayIntakes();
|
||||||
|
// Also refresh monthly intakes if they're loaded
|
||||||
|
if (_monthlyIntakes.isNotEmpty) {
|
||||||
|
await loadMonthlyIntakes(DateTime.now().year, DateTime.now().month);
|
||||||
|
}
|
||||||
|
notifyListeners();
|
||||||
|
|
||||||
|
// Trigger sync after permanently deleting intake
|
||||||
|
_triggerSyncIfEnabled();
|
||||||
|
} catch (e) {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('Error permanently deleting intake: $e');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -401,10 +370,26 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
return _todayIntakes.where((intake) => intake['supplement_id'] == supplementId).length;
|
return _todayIntakes.where((intake) => intake['supplement_id'] == supplementId).length;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Map<String, double> get dailyIngredientIntake {
|
||||||
|
final Map<String, double> ingredientIntake = {};
|
||||||
|
|
||||||
|
for (final intake in _todayIntakes) {
|
||||||
|
final supplement = _supplements.firstWhere((s) => s.id == intake['supplement_id']);
|
||||||
|
final unitsTaken = intake['unitsTaken'] as double;
|
||||||
|
|
||||||
|
for (final ingredient in supplement.ingredients) {
|
||||||
|
final currentAmount = ingredientIntake[ingredient.name] ?? 0;
|
||||||
|
ingredientIntake[ingredient.name] = currentAmount + (ingredient.amount * unitsTaken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ingredientIntake;
|
||||||
|
}
|
||||||
|
|
||||||
// Method to manually refresh daily status (useful for testing or manual refresh)
|
// Method to manually refresh daily status (useful for testing or manual refresh)
|
||||||
Future<void> refreshDailyStatus() async {
|
Future<void> refreshDailyStatus() async {
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('Manually refreshing daily status...');
|
printLog('Manually refreshing daily status...');
|
||||||
}
|
}
|
||||||
_lastDateCheck = DateTime.now();
|
_lastDateCheck = DateTime.now();
|
||||||
await loadTodayIntakes();
|
await loadTodayIntakes();
|
||||||
@@ -417,20 +402,20 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
final lastCheckDate = DateTime(_lastDateCheck.year, _lastDateCheck.month, _lastDateCheck.day);
|
final lastCheckDate = DateTime(_lastDateCheck.year, _lastDateCheck.month, _lastDateCheck.day);
|
||||||
|
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('Force checking date change...');
|
printLog('Force checking date change...');
|
||||||
print('Current date: $currentDate');
|
printLog('Current date: $currentDate');
|
||||||
print('Last check date: $lastCheckDate');
|
printLog('Last check date: $lastCheckDate');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (currentDate != lastCheckDate) {
|
if (currentDate != lastCheckDate) {
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('Date change detected, refreshing intakes...');
|
printLog('Date change detected, refreshing intakes...');
|
||||||
}
|
}
|
||||||
_lastDateCheck = now;
|
_lastDateCheck = now;
|
||||||
await loadTodayIntakes();
|
await loadTodayIntakes();
|
||||||
} else {
|
} else {
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('No date change detected');
|
printLog('No date change detected');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -445,7 +430,7 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
notifyListeners();
|
notifyListeners();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('Error loading archived supplements: $e');
|
printLog('Error loading archived supplements: $e');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -460,7 +445,7 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
_triggerSyncIfEnabled();
|
_triggerSyncIfEnabled();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('Error archiving supplement: $e');
|
printLog('Error archiving supplement: $e');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -475,46 +460,53 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
_triggerSyncIfEnabled();
|
_triggerSyncIfEnabled();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('Error unarchiving supplement: $e');
|
printLog('Error unarchiving supplement: $e');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> deleteArchivedSupplement(int supplementId) async {
|
Future<void> deleteArchivedSupplement(int supplementId) async {
|
||||||
try {
|
try {
|
||||||
await _databaseHelper.deleteSupplement(supplementId);
|
await _databaseHelper.permanentlyDeleteSupplement(supplementId);
|
||||||
await loadArchivedSupplements(); // Refresh archived supplements
|
await loadArchivedSupplements(); // Refresh archived supplements
|
||||||
|
|
||||||
// Trigger sync after deleting archived supplement
|
// Trigger sync after permanently deleting archived supplement
|
||||||
_triggerSyncIfEnabled();
|
_triggerSyncIfEnabled();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
print('Error deleting archived supplement: $e');
|
printLog('Error permanently deleting archived supplement: $e');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Debug methods for notification testing
|
// Debug methods for notification testing
|
||||||
Future<void> testNotifications() async {
|
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 {
|
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 {
|
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 {
|
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
|
// Debug method to test notification persistence
|
||||||
Future<void> rescheduleAllNotifications() async {
|
Future<void> rescheduleAllNotifications() async {
|
||||||
@@ -523,6 +515,6 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
|
|
||||||
// Debug method to cancel all notifications
|
// Debug method to cancel all notifications
|
||||||
Future<void> cancelAllNotifications() async {
|
Future<void> cancelAllNotifications() async {
|
||||||
await _notificationService.cancelAllReminders();
|
await _notificationService.cancelAll();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,417 +0,0 @@
|
|||||||
import 'package:flutter/foundation.dart';
|
|
||||||
|
|
||||||
import '../models/sync_data.dart';
|
|
||||||
import '../models/sync_enums.dart';
|
|
||||||
import '../services/webdav_sync_service.dart';
|
|
||||||
import 'supplement_provider.dart';
|
|
||||||
|
|
||||||
/// Provider for managing sync operations with WebDAV servers
|
|
||||||
class SyncProvider with ChangeNotifier {
|
|
||||||
final WebDAVSyncService _syncService = WebDAVSyncService();
|
|
||||||
final SupplementProvider _supplementProvider;
|
|
||||||
|
|
||||||
SyncOperationStatus _status = SyncOperationStatus.idle;
|
|
||||||
SyncResult? _lastSyncResult;
|
|
||||||
DateTime? _lastSyncTime;
|
|
||||||
String? _currentError;
|
|
||||||
bool _isAutoSyncEnabled = false;
|
|
||||||
bool _autoSyncOnDataChanges = true;
|
|
||||||
SyncFrequency _syncFrequency = SyncFrequency.hourly;
|
|
||||||
ConflictResolutionStrategy _conflictStrategy = ConflictResolutionStrategy.manual;
|
|
||||||
List<SyncConflict> _pendingConflicts = [];
|
|
||||||
double _syncProgress = 0.0;
|
|
||||||
|
|
||||||
// WebDAV Configuration
|
|
||||||
String? _serverUrl;
|
|
||||||
String? _username;
|
|
||||||
String? _detectedServerType;
|
|
||||||
String? _finalWebdavUrl;
|
|
||||||
String? _syncFolderName;
|
|
||||||
bool _isConfigured = false;
|
|
||||||
|
|
||||||
SyncProvider(this._supplementProvider);
|
|
||||||
|
|
||||||
// Getters
|
|
||||||
SyncOperationStatus get status => _status;
|
|
||||||
SyncResult? get lastSyncResult => _lastSyncResult;
|
|
||||||
DateTime? get lastSyncTime => _lastSyncTime;
|
|
||||||
String? get currentError => _currentError;
|
|
||||||
bool get isAutoSyncEnabled => _isAutoSyncEnabled;
|
|
||||||
bool get autoSyncOnDataChanges => _autoSyncOnDataChanges;
|
|
||||||
SyncFrequency get syncFrequency => _syncFrequency;
|
|
||||||
ConflictResolutionStrategy get conflictStrategy => _conflictStrategy;
|
|
||||||
List<SyncConflict> get pendingConflicts => List.unmodifiable(_pendingConflicts);
|
|
||||||
double get syncProgress => _syncProgress;
|
|
||||||
String? get serverUrl => _serverUrl;
|
|
||||||
String? get username => _username;
|
|
||||||
String? get detectedServerType => _detectedServerType;
|
|
||||||
String? get finalWebdavUrl => _finalWebdavUrl;
|
|
||||||
String? get syncFolderName => _syncFolderName;
|
|
||||||
bool get isConfigured => _isConfigured;
|
|
||||||
bool get isSyncing => _status == SyncOperationStatus.syncing;
|
|
||||||
bool get hasError => _currentError != null;
|
|
||||||
bool get hasPendingConflicts => _pendingConflicts.isNotEmpty;
|
|
||||||
|
|
||||||
/// Initialize the sync provider
|
|
||||||
Future<void> initialize() async {
|
|
||||||
await _syncService.initialize();
|
|
||||||
_isConfigured = await _syncService.isConfigured();
|
|
||||||
_lastSyncTime = await _syncService.getLastSyncTime();
|
|
||||||
|
|
||||||
if (_isConfigured) {
|
|
||||||
// Load existing configuration
|
|
||||||
_serverUrl = await _syncService.getServerUrl();
|
|
||||||
_username = await _syncService.getUsername();
|
|
||||||
_syncFolderName = await _syncService.getSyncFolderName();
|
|
||||||
_finalWebdavUrl = await _syncService.getLastWorkingUrl();
|
|
||||||
_detectedServerType = _detectServerTypeFromUrl(_finalWebdavUrl ?? _serverUrl ?? '');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set up data change callback on supplement provider
|
|
||||||
_supplementProvider.setOnDataChangedCallback(() {
|
|
||||||
triggerAutoSyncOnDataChange();
|
|
||||||
});
|
|
||||||
|
|
||||||
notifyListeners();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Configure WebDAV connection
|
|
||||||
Future<bool> configure({
|
|
||||||
required String serverUrl,
|
|
||||||
required String username,
|
|
||||||
String? password,
|
|
||||||
String? deviceName,
|
|
||||||
String? syncFolderName,
|
|
||||||
}) async {
|
|
||||||
try {
|
|
||||||
_setStatus(SyncOperationStatus.syncing);
|
|
||||||
_clearError();
|
|
||||||
|
|
||||||
final success = await _syncService.configure(
|
|
||||||
baseUrl: serverUrl,
|
|
||||||
username: username,
|
|
||||||
password: password,
|
|
||||||
deviceName: deviceName,
|
|
||||||
syncFolderName: syncFolderName ?? 'Supplements',
|
|
||||||
);
|
|
||||||
|
|
||||||
if (success) {
|
|
||||||
_serverUrl = serverUrl;
|
|
||||||
_username = username;
|
|
||||||
_syncFolderName = syncFolderName ?? 'Supplements';
|
|
||||||
_isConfigured = true;
|
|
||||||
|
|
||||||
// Get server detection info
|
|
||||||
_finalWebdavUrl = await _syncService.getLastWorkingUrl();
|
|
||||||
_detectedServerType = _detectServerTypeFromUrl(_finalWebdavUrl ?? serverUrl);
|
|
||||||
|
|
||||||
_setStatus(SyncOperationStatus.success);
|
|
||||||
} else {
|
|
||||||
_setError('Failed to configure WebDAV connection', SyncOperationStatus.authenticationError);
|
|
||||||
}
|
|
||||||
|
|
||||||
return success;
|
|
||||||
} catch (e) {
|
|
||||||
_setError(e.toString(), SyncOperationStatus.authenticationError);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Test WebDAV connection
|
|
||||||
Future<bool> testConnection() async {
|
|
||||||
if (!_isConfigured) return false;
|
|
||||||
|
|
||||||
try {
|
|
||||||
_clearError();
|
|
||||||
return await _syncService.testConnection();
|
|
||||||
} catch (e) {
|
|
||||||
_setError(e.toString(), SyncOperationStatus.networkError);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Clear WebDAV configuration
|
|
||||||
Future<void> clearConfiguration() async {
|
|
||||||
await _syncService.clearConfiguration();
|
|
||||||
_serverUrl = null;
|
|
||||||
_username = null;
|
|
||||||
_detectedServerType = null;
|
|
||||||
_finalWebdavUrl = null;
|
|
||||||
_syncFolderName = null;
|
|
||||||
_isConfigured = false;
|
|
||||||
_setStatus(SyncOperationStatus.idle);
|
|
||||||
_clearError();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Perform manual sync
|
|
||||||
Future<bool> performManualSync() async {
|
|
||||||
if (!_isConfigured || _status == SyncOperationStatus.syncing) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
_setStatus(SyncOperationStatus.syncing);
|
|
||||||
_clearError();
|
|
||||||
_syncProgress = 0.0;
|
|
||||||
|
|
||||||
// Check connectivity first
|
|
||||||
if (!await _syncService.hasConnectivity()) {
|
|
||||||
_setError('No internet connection', SyncOperationStatus.networkError);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
_syncProgress = 0.2;
|
|
||||||
notifyListeners();
|
|
||||||
|
|
||||||
// Perform the sync
|
|
||||||
final result = await _syncService.performSync();
|
|
||||||
_lastSyncResult = result;
|
|
||||||
_lastSyncTime = result.timestamp;
|
|
||||||
|
|
||||||
_syncProgress = 0.8;
|
|
||||||
notifyListeners();
|
|
||||||
|
|
||||||
if (result.success) {
|
|
||||||
if (result.conflicts.isNotEmpty) {
|
|
||||||
_pendingConflicts = result.conflicts;
|
|
||||||
_setStatus(SyncOperationStatus.conflictsDetected);
|
|
||||||
} else {
|
|
||||||
_setStatus(SyncOperationStatus.success);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reload local data after successful sync
|
|
||||||
await _supplementProvider.loadSupplements();
|
|
||||||
await _supplementProvider.loadTodayIntakes();
|
|
||||||
} else {
|
|
||||||
_setError(result.error ?? 'Sync failed', result.status);
|
|
||||||
}
|
|
||||||
|
|
||||||
_syncProgress = 1.0;
|
|
||||||
notifyListeners();
|
|
||||||
|
|
||||||
return result.success;
|
|
||||||
} catch (e) {
|
|
||||||
_setError(e.toString(), SyncOperationStatus.serverError);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Resolve a conflict
|
|
||||||
Future<void> resolveConflict(String syncId, ConflictResolution resolution) async {
|
|
||||||
_pendingConflicts.removeWhere((conflict) => conflict.syncId == syncId);
|
|
||||||
|
|
||||||
// TODO: Implement actual conflict resolution logic
|
|
||||||
// This would involve updating the local database with the chosen resolution
|
|
||||||
|
|
||||||
if (_pendingConflicts.isEmpty && _status == SyncOperationStatus.conflictsDetected) {
|
|
||||||
_setStatus(SyncOperationStatus.success);
|
|
||||||
}
|
|
||||||
|
|
||||||
notifyListeners();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Resolve all conflicts using the configured strategy
|
|
||||||
Future<void> resolveAllConflicts() async {
|
|
||||||
if (_conflictStrategy == ConflictResolutionStrategy.manual) {
|
|
||||||
return; // Manual conflicts need individual resolution
|
|
||||||
}
|
|
||||||
|
|
||||||
final resolvedConflicts = <SyncConflict>[];
|
|
||||||
|
|
||||||
for (final conflict in _pendingConflicts) {
|
|
||||||
ConflictResolution resolution;
|
|
||||||
|
|
||||||
switch (_conflictStrategy) {
|
|
||||||
case ConflictResolutionStrategy.preferLocal:
|
|
||||||
resolution = ConflictResolution.useLocal;
|
|
||||||
break;
|
|
||||||
case ConflictResolutionStrategy.preferRemote:
|
|
||||||
resolution = ConflictResolution.useRemote;
|
|
||||||
break;
|
|
||||||
case ConflictResolutionStrategy.preferNewer:
|
|
||||||
resolution = conflict.isLocalNewer
|
|
||||||
? ConflictResolution.useLocal
|
|
||||||
: ConflictResolution.useRemote;
|
|
||||||
break;
|
|
||||||
case ConflictResolutionStrategy.manual:
|
|
||||||
continue; // Skip manual conflicts
|
|
||||||
}
|
|
||||||
|
|
||||||
await resolveConflict(conflict.syncId, resolution);
|
|
||||||
resolvedConflicts.add(conflict);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (resolvedConflicts.isNotEmpty) {
|
|
||||||
// Perform another sync to apply resolutions
|
|
||||||
await performManualSync();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Enable or disable auto sync
|
|
||||||
Future<void> setAutoSyncEnabled(bool enabled) async {
|
|
||||||
_isAutoSyncEnabled = enabled;
|
|
||||||
notifyListeners();
|
|
||||||
|
|
||||||
if (enabled) {
|
|
||||||
_scheduleNextAutoSync();
|
|
||||||
}
|
|
||||||
// TODO: Cancel existing timers when disabled
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set sync frequency
|
|
||||||
Future<void> setSyncFrequency(SyncFrequency frequency) async {
|
|
||||||
_syncFrequency = frequency;
|
|
||||||
notifyListeners();
|
|
||||||
|
|
||||||
if (_isAutoSyncEnabled) {
|
|
||||||
_scheduleNextAutoSync();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set conflict resolution strategy
|
|
||||||
Future<void> setConflictResolutionStrategy(ConflictResolutionStrategy strategy) async {
|
|
||||||
_conflictStrategy = strategy;
|
|
||||||
notifyListeners();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Enable or disable auto sync on data changes
|
|
||||||
Future<void> setAutoSyncOnDataChanges(bool enabled) async {
|
|
||||||
_autoSyncOnDataChanges = enabled;
|
|
||||||
notifyListeners();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Trigger sync automatically when data changes (if enabled)
|
|
||||||
Future<void> triggerAutoSyncOnDataChange() async {
|
|
||||||
if (!_autoSyncOnDataChanges || !_isConfigured || _status == SyncOperationStatus.syncing) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Perform sync without blocking the UI
|
|
||||||
performManualSync();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get sync statistics from last result
|
|
||||||
SyncStatistics? get lastSyncStatistics => _lastSyncResult?.statistics;
|
|
||||||
|
|
||||||
/// Get formatted last sync time
|
|
||||||
String get formattedLastSyncTime {
|
|
||||||
if (_lastSyncTime == null) return 'Never';
|
|
||||||
|
|
||||||
final now = DateTime.now();
|
|
||||||
final difference = now.difference(_lastSyncTime!);
|
|
||||||
|
|
||||||
if (difference.inMinutes < 1) {
|
|
||||||
return 'Just now';
|
|
||||||
} else if (difference.inMinutes < 60) {
|
|
||||||
return '${difference.inMinutes}m ago';
|
|
||||||
} else if (difference.inHours < 24) {
|
|
||||||
return '${difference.inHours}h ago';
|
|
||||||
} else {
|
|
||||||
return '${difference.inDays}d ago';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get sync status message
|
|
||||||
String get statusMessage {
|
|
||||||
switch (_status) {
|
|
||||||
case SyncOperationStatus.idle:
|
|
||||||
return 'Ready to sync';
|
|
||||||
case SyncOperationStatus.syncing:
|
|
||||||
return 'Syncing... ${(_syncProgress * 100).round()}%';
|
|
||||||
case SyncOperationStatus.success:
|
|
||||||
return 'Sync completed successfully';
|
|
||||||
case SyncOperationStatus.networkError:
|
|
||||||
return 'Network connection failed';
|
|
||||||
case SyncOperationStatus.authenticationError:
|
|
||||||
return 'Authentication failed';
|
|
||||||
case SyncOperationStatus.serverError:
|
|
||||||
return 'Server error occurred';
|
|
||||||
case SyncOperationStatus.conflictsDetected:
|
|
||||||
return '${_pendingConflicts.length} conflict(s) need resolution';
|
|
||||||
case SyncOperationStatus.cancelled:
|
|
||||||
return 'Sync was cancelled';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get device info
|
|
||||||
Future<Map<String, String?>> getDeviceInfo() async {
|
|
||||||
return await _syncService.getDeviceInfo();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Private methods
|
|
||||||
|
|
||||||
void _setStatus(SyncOperationStatus status) {
|
|
||||||
_status = status;
|
|
||||||
notifyListeners();
|
|
||||||
}
|
|
||||||
|
|
||||||
void _setError(String error, SyncOperationStatus status) {
|
|
||||||
_currentError = error;
|
|
||||||
_status = status;
|
|
||||||
_syncProgress = 0.0;
|
|
||||||
notifyListeners();
|
|
||||||
}
|
|
||||||
|
|
||||||
void _clearError() {
|
|
||||||
_currentError = null;
|
|
||||||
notifyListeners();
|
|
||||||
}
|
|
||||||
|
|
||||||
void _scheduleNextAutoSync() {
|
|
||||||
if (!_isAutoSyncEnabled || _syncFrequency == SyncFrequency.manual) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: Implement actual scheduling logic using Timer or WorkManager
|
|
||||||
// This would schedule the next automatic sync based on the frequency
|
|
||||||
if (kDebugMode) {
|
|
||||||
print('Next auto sync scheduled for ${_syncFrequency.displayName}');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Detect server type from URL for display purposes
|
|
||||||
String _detectServerTypeFromUrl(String url) {
|
|
||||||
final lowerUrl = url.toLowerCase();
|
|
||||||
|
|
||||||
if (lowerUrl.contains('/remote.php/dav/files/')) {
|
|
||||||
return 'Nextcloud';
|
|
||||||
} else if (lowerUrl.contains('/remote.php/webdav/')) {
|
|
||||||
return 'ownCloud';
|
|
||||||
} else if (lowerUrl.contains('nextcloud')) {
|
|
||||||
return 'Nextcloud';
|
|
||||||
} else if (lowerUrl.contains('owncloud')) {
|
|
||||||
return 'ownCloud';
|
|
||||||
} else if (lowerUrl.contains('/webdav/') || lowerUrl.contains('/dav/')) {
|
|
||||||
return 'Generic WebDAV';
|
|
||||||
} else {
|
|
||||||
return 'WebDAV Server';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void dispose() {
|
|
||||||
// TODO: Cancel any pending timers or background tasks
|
|
||||||
super.dispose();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Enum for conflict resolution choices
|
|
||||||
enum ConflictResolution {
|
|
||||||
useLocal,
|
|
||||||
useRemote,
|
|
||||||
merge, // For future implementation
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Extension methods for ConflictResolution
|
|
||||||
extension ConflictResolutionExtension on ConflictResolution {
|
|
||||||
String get displayName {
|
|
||||||
switch (this) {
|
|
||||||
case ConflictResolution.useLocal:
|
|
||||||
return 'Use Local Version';
|
|
||||||
case ConflictResolution.useRemote:
|
|
||||||
return 'Use Remote Version';
|
|
||||||
case ConflictResolution.merge:
|
|
||||||
return 'Merge Changes';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ class _AddSupplementScreenState extends State<AddSupplementScreen> {
|
|||||||
final _notesController = TextEditingController();
|
final _notesController = TextEditingController();
|
||||||
|
|
||||||
// Multi-ingredient support with persistent controllers
|
// Multi-ingredient support with persistent controllers
|
||||||
List<IngredientController> _ingredientControllers = [];
|
final _ingredientControllers = [];
|
||||||
|
|
||||||
String _selectedUnitType = 'capsules';
|
String _selectedUnitType = 'capsules';
|
||||||
int _frequencyPerDay = 1;
|
int _frequencyPerDay = 1;
|
||||||
@@ -224,6 +224,13 @@ class _AddSupplementScreenState extends State<AddSupplementScreen> {
|
|||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
title: Text(isEditing ? 'Edit Supplement' : 'Add Supplement'),
|
title: Text(isEditing ? 'Edit Supplement' : 'Add Supplement'),
|
||||||
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
|
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
|
||||||
|
actions: [
|
||||||
|
IconButton(
|
||||||
|
tooltip: isEditing ? 'Update Supplement' : 'Save Supplement',
|
||||||
|
onPressed: _saveSupplement,
|
||||||
|
icon: const Icon(Icons.save),
|
||||||
|
),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
body: Form(
|
body: Form(
|
||||||
key: _formKey,
|
key: _formKey,
|
||||||
@@ -482,17 +489,7 @@ class _AddSupplementScreenState extends State<AddSupplementScreen> {
|
|||||||
),
|
),
|
||||||
const SizedBox(height: 24),
|
const SizedBox(height: 24),
|
||||||
|
|
||||||
// Save button
|
// Save is now in the AppBar for consistency with app-wide pattern
|
||||||
SizedBox(
|
|
||||||
width: double.infinity,
|
|
||||||
child: ElevatedButton(
|
|
||||||
onPressed: _saveSupplement,
|
|
||||||
style: ElevatedButton.styleFrom(
|
|
||||||
padding: const EdgeInsets.all(16),
|
|
||||||
),
|
|
||||||
child: Text(isEditing ? 'Update Supplement' : 'Add Supplement'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -560,21 +557,24 @@ class _AddSupplementScreenState extends State<AddSupplementScreen> {
|
|||||||
void _saveSupplement() async {
|
void _saveSupplement() async {
|
||||||
if (_formKey.currentState!.validate()) {
|
if (_formKey.currentState!.validate()) {
|
||||||
// Validate that we have at least one ingredient with name and amount
|
// Validate that we have at least one ingredient with name and amount
|
||||||
final validIngredients = _ingredientControllers.where((controller) =>
|
final validIngredients = _ingredientControllers
|
||||||
|
.where((controller) =>
|
||||||
controller.nameController.text.trim().isNotEmpty &&
|
controller.nameController.text.trim().isNotEmpty &&
|
||||||
(double.tryParse(controller.amountController.text) ?? 0) > 0
|
(double.tryParse(controller.amountController.text) ?? 0) > 0)
|
||||||
).map((controller) => Ingredient(
|
.map((controller) => Ingredient(
|
||||||
name: controller.nameController.text.trim(),
|
name: controller.nameController.text.trim(),
|
||||||
amount: double.tryParse(controller.amountController.text) ?? 0.0,
|
amount: double.tryParse(controller.amountController.text) ?? 0.0,
|
||||||
unit: controller.selectedUnit,
|
unit: controller.selectedUnit,
|
||||||
syncId: const Uuid().v4(),
|
syncId: const Uuid().v4(),
|
||||||
lastModified: DateTime.now(),
|
lastModified: DateTime.now(),
|
||||||
)).toList();
|
))
|
||||||
|
.toList();
|
||||||
|
|
||||||
if (validIngredients.isEmpty) {
|
if (validIngredients.isEmpty) {
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
const SnackBar(
|
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;
|
return;
|
||||||
@@ -583,14 +583,20 @@ class _AddSupplementScreenState extends State<AddSupplementScreen> {
|
|||||||
final supplement = Supplement(
|
final supplement = Supplement(
|
||||||
id: widget.supplement?.id,
|
id: widget.supplement?.id,
|
||||||
name: _nameController.text.trim(),
|
name: _nameController.text.trim(),
|
||||||
brand: _brandController.text.trim().isNotEmpty ? _brandController.text.trim() : null,
|
brand: _brandController.text.trim().isNotEmpty
|
||||||
|
? _brandController.text.trim()
|
||||||
|
: null,
|
||||||
ingredients: validIngredients,
|
ingredients: validIngredients,
|
||||||
numberOfUnits: int.parse(_numberOfUnitsController.text),
|
numberOfUnits: int.parse(_numberOfUnitsController.text),
|
||||||
unitType: _selectedUnitType,
|
unitType: _selectedUnitType,
|
||||||
frequencyPerDay: _frequencyPerDay,
|
frequencyPerDay: _frequencyPerDay,
|
||||||
reminderTimes: _reminderTimes,
|
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(),
|
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>();
|
final provider = context.read<SupplementProvider>();
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
|
import 'package:supplements/widgets/info_chip.dart';
|
||||||
|
|
||||||
import '../models/supplement.dart';
|
import '../models/supplement.dart';
|
||||||
import '../providers/supplement_provider.dart';
|
import '../providers/supplement_provider.dart';
|
||||||
import '../providers/sync_provider.dart';
|
|
||||||
|
|
||||||
class ArchivedSupplementsScreen extends StatefulWidget {
|
class ArchivedSupplementsScreen extends StatefulWidget {
|
||||||
const ArchivedSupplementsScreen({super.key});
|
const ArchivedSupplementsScreen({super.key});
|
||||||
@@ -27,35 +27,9 @@ class _ArchivedSupplementsScreenState extends State<ArchivedSupplementsScreen> {
|
|||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
title: const Text('Archived Supplements'),
|
title: const Text('Archived Supplements'),
|
||||||
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
|
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
|
||||||
actions: [
|
|
||||||
Consumer<SyncProvider>(
|
|
||||||
builder: (context, syncProvider, child) {
|
|
||||||
if (!syncProvider.isConfigured) {
|
|
||||||
return const SizedBox.shrink();
|
|
||||||
}
|
|
||||||
|
|
||||||
return IconButton(
|
|
||||||
icon: syncProvider.isSyncing
|
|
||||||
? const SizedBox(
|
|
||||||
width: 20,
|
|
||||||
height: 20,
|
|
||||||
child: CircularProgressIndicator(strokeWidth: 2),
|
|
||||||
)
|
|
||||||
: syncProvider.status.name == 'success' &&
|
|
||||||
DateTime.now().difference(syncProvider.lastSyncTime ?? DateTime.now()).inSeconds < 5
|
|
||||||
? const Icon(Icons.check, color: Colors.green)
|
|
||||||
: const Icon(Icons.sync),
|
|
||||||
onPressed: syncProvider.isSyncing ? null : () {
|
|
||||||
syncProvider.performManualSync();
|
|
||||||
},
|
|
||||||
tooltip: syncProvider.isSyncing ? 'Syncing...' : 'Force Sync',
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
),
|
||||||
],
|
body: Consumer<SupplementProvider>(
|
||||||
),
|
builder: (context, provider, child) {
|
||||||
body: Consumer2<SupplementProvider, SyncProvider>(
|
|
||||||
builder: (context, provider, syncProvider, child) {
|
|
||||||
if (provider.archivedSupplements.isEmpty) {
|
if (provider.archivedSupplements.isEmpty) {
|
||||||
return Center(
|
return Center(
|
||||||
child: Column(
|
child: Column(
|
||||||
@@ -333,13 +307,13 @@ class _ArchivedSupplementCard extends StatelessWidget {
|
|||||||
// Dosage info
|
// Dosage info
|
||||||
Row(
|
Row(
|
||||||
children: [
|
children: [
|
||||||
_InfoChip(
|
InfoChip(
|
||||||
icon: Icons.schedule,
|
icon: Icons.schedule,
|
||||||
label: '${supplement.frequencyPerDay}x daily',
|
label: '${supplement.frequencyPerDay}x daily',
|
||||||
context: context,
|
context: context,
|
||||||
),
|
),
|
||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
_InfoChip(
|
InfoChip(
|
||||||
icon: Icons.medication,
|
icon: Icons.medication,
|
||||||
label: '${supplement.numberOfUnits} ${supplement.unitType}',
|
label: '${supplement.numberOfUnits} ${supplement.unitType}',
|
||||||
context: context,
|
context: context,
|
||||||
@@ -349,7 +323,7 @@ class _ArchivedSupplementCard extends StatelessWidget {
|
|||||||
|
|
||||||
if (supplement.reminderTimes.isNotEmpty) ...[
|
if (supplement.reminderTimes.isNotEmpty) ...[
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
_InfoChip(
|
InfoChip(
|
||||||
icon: Icons.notifications_off,
|
icon: Icons.notifications_off,
|
||||||
label: 'Was: ${supplement.reminderTimes.join(', ')}',
|
label: 'Was: ${supplement.reminderTimes.join(', ')}',
|
||||||
context: context,
|
context: context,
|
||||||
@@ -363,51 +337,3 @@ class _ArchivedSupplementCard extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class _InfoChip extends StatelessWidget {
|
|
||||||
final IconData icon;
|
|
||||||
final String label;
|
|
||||||
final BuildContext context;
|
|
||||||
final bool fullWidth;
|
|
||||||
|
|
||||||
const _InfoChip({
|
|
||||||
required this.icon,
|
|
||||||
required this.label,
|
|
||||||
required this.context,
|
|
||||||
this.fullWidth = false,
|
|
||||||
});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return Container(
|
|
||||||
width: fullWidth ? double.infinity : null,
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.4),
|
|
||||||
borderRadius: BorderRadius.circular(8),
|
|
||||||
),
|
|
||||||
child: Row(
|
|
||||||
mainAxisSize: fullWidth ? MainAxisSize.max : MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
Icon(
|
|
||||||
icon,
|
|
||||||
size: 14,
|
|
||||||
color: Theme.of(context).colorScheme.outline,
|
|
||||||
),
|
|
||||||
const SizedBox(width: 4),
|
|
||||||
Flexible(
|
|
||||||
child: Text(
|
|
||||||
label,
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 11,
|
|
||||||
color: Theme.of(context).colorScheme.outline,
|
|
||||||
fontWeight: FontWeight.w500,
|
|
||||||
),
|
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
415
lib/screens/debug_notifications_screen.dart
Normal file
415
lib/screens/debug_notifications_screen.dart
Normal file
@@ -0,0 +1,415 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||||
|
import 'package:provider/provider.dart';
|
||||||
|
import 'package:supplements/providers/supplement_provider.dart';
|
||||||
|
import 'package:supplements/services/notification_debug_store.dart';
|
||||||
|
import 'package:supplements/services/simple_notification_service.dart';
|
||||||
|
|
||||||
|
class DebugNotificationsScreen extends StatefulWidget {
|
||||||
|
const DebugNotificationsScreen({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<DebugNotificationsScreen> createState() => _DebugNotificationsScreenState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _DebugNotificationsScreenState extends State<DebugNotificationsScreen> {
|
||||||
|
bool _loading = true;
|
||||||
|
List<PendingNotificationRequest> _pending = const [];
|
||||||
|
List<NotificationLogEntry> _logEntries = const [];
|
||||||
|
final Map<int, String> _supplementNameCache = {};
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_load();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _load() async {
|
||||||
|
setState(() {
|
||||||
|
_loading = true;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Fetch pending from plugin
|
||||||
|
final pending = await SimpleNotificationService.instance.getPendingNotifications();
|
||||||
|
|
||||||
|
// Fetch log from local store
|
||||||
|
final logs = await NotificationDebugStore.instance.getAll();
|
||||||
|
|
||||||
|
// Optionally resolve supplement names for single payloads
|
||||||
|
await _resolveSupplementNames(pending, logs);
|
||||||
|
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_pending = pending;
|
||||||
|
_logEntries = logs.reversed.toList(); // newest first
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _resolveSupplementNames(
|
||||||
|
List<PendingNotificationRequest> pending,
|
||||||
|
List<NotificationLogEntry> logs,
|
||||||
|
) async {
|
||||||
|
final ctx = context;
|
||||||
|
if (!mounted) return;
|
||||||
|
final provider = Provider.of<SupplementProvider>(ctx, listen: false);
|
||||||
|
// Use existing list; attempt load if empty
|
||||||
|
if (provider.supplements.isEmpty) {
|
||||||
|
try {
|
||||||
|
await provider.loadSupplements();
|
||||||
|
} catch (_) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect potential IDs
|
||||||
|
final Set<int> ids = {};
|
||||||
|
for (final p in pending) {
|
||||||
|
final id = _extractSingleIdFromPayload(p.payload);
|
||||||
|
if (id != null) ids.add(id);
|
||||||
|
}
|
||||||
|
for (final e in logs) {
|
||||||
|
if (e.singleId != null) ids.add(e.singleId!);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build cache
|
||||||
|
for (final id in ids) {
|
||||||
|
try {
|
||||||
|
final s = provider.supplements.firstWhere((el) => el.id == id);
|
||||||
|
_supplementNameCache[id] = s.name;
|
||||||
|
} catch (_) {
|
||||||
|
// leave missing
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int? _extractSingleIdFromPayload(String? payload) {
|
||||||
|
if (payload == null || payload.isEmpty) return null;
|
||||||
|
try {
|
||||||
|
final map = jsonDecode(payload);
|
||||||
|
if (map is Map && map['type'] == 'single') {
|
||||||
|
final v = map['id'];
|
||||||
|
if (v is int) return v;
|
||||||
|
}
|
||||||
|
} catch (_) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
String? _extractGroupTimeFromPayload(String? payload) {
|
||||||
|
if (payload == null || payload.isEmpty) return null;
|
||||||
|
try {
|
||||||
|
final map = jsonDecode(payload);
|
||||||
|
if (map is Map && map['type'] == 'group') {
|
||||||
|
final v = map['time'];
|
||||||
|
if (v is String) return v;
|
||||||
|
}
|
||||||
|
} catch (_) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
String _extractKindFromPayload(String? payload) {
|
||||||
|
if (payload == null || payload.isEmpty) return 'unknown';
|
||||||
|
try {
|
||||||
|
final map = jsonDecode(payload);
|
||||||
|
if (map is Map) {
|
||||||
|
final meta = map['meta'];
|
||||||
|
if (meta is Map && meta['kind'] is String) return meta['kind'] as String;
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
return 'unknown';
|
||||||
|
}
|
||||||
|
|
||||||
|
DateTime? _estimateScheduledAtFromPayload(String? payload) {
|
||||||
|
// For snooze with meta.createdAt/delayMin we can compute when.
|
||||||
|
if (payload == null || payload.isEmpty) return null;
|
||||||
|
try {
|
||||||
|
final map = jsonDecode(payload);
|
||||||
|
if (map is Map) {
|
||||||
|
final meta = map['meta'];
|
||||||
|
if (meta is Map) {
|
||||||
|
final kind = meta['kind'];
|
||||||
|
if (kind == 'snooze') {
|
||||||
|
final createdAt = meta['createdAt'];
|
||||||
|
final delayMin = meta['delayMin'];
|
||||||
|
if (createdAt is int && delayMin is int) {
|
||||||
|
return DateTime.fromMillisecondsSinceEpoch(createdAt)
|
||||||
|
.add(Duration(minutes: delayMin));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// For daily group we can compute next HH:mm
|
||||||
|
if (map['type'] == 'group' && map['time'] is String) {
|
||||||
|
final timeKey = map['time'] as String;
|
||||||
|
final parts = timeKey.split(':');
|
||||||
|
if (parts.length == 2) {
|
||||||
|
final hour = int.tryParse(parts[0]) ?? 0;
|
||||||
|
final minute = int.tryParse(parts[1]) ?? 0;
|
||||||
|
final now = DateTime.now();
|
||||||
|
DateTime sched = DateTime(now.year, now.month, now.day, hour, minute);
|
||||||
|
if (!sched.isAfter(now)) {
|
||||||
|
sched = sched.add(const Duration(days: 1));
|
||||||
|
}
|
||||||
|
return sched;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _cancelId(int id) async {
|
||||||
|
await SimpleNotificationService.instance.cancelById(id);
|
||||||
|
await _load();
|
||||||
|
if (!mounted) return;
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Canceled notification $id')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _cancelAll() async {
|
||||||
|
await SimpleNotificationService.instance.cancelAll();
|
||||||
|
await _load();
|
||||||
|
if (!mounted) return;
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
const SnackBar(content: Text('Canceled all notifications')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _clearLog() async {
|
||||||
|
await NotificationDebugStore.instance.clear();
|
||||||
|
await _load();
|
||||||
|
if (!mounted) return;
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
const SnackBar(content: Text('Cleared debug log')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _copyToClipboard(String text) {
|
||||||
|
Clipboard.setData(ClipboardData(text: text));
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
const SnackBar(content: Text('Copied to clipboard')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final pendingIds = _pending.map((e) => e.id).toSet();
|
||||||
|
|
||||||
|
return Scaffold(
|
||||||
|
appBar: AppBar(
|
||||||
|
title: const Text('Debug Notifications'),
|
||||||
|
actions: [
|
||||||
|
IconButton(
|
||||||
|
tooltip: 'Refresh',
|
||||||
|
onPressed: _load,
|
||||||
|
icon: const Icon(Icons.refresh),
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
tooltip: 'Cancel All',
|
||||||
|
onPressed: _cancelAll,
|
||||||
|
icon: const Icon(Icons.cancel_schedule_send),
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
tooltip: 'Clear Log',
|
||||||
|
onPressed: _clearLog,
|
||||||
|
icon: const Icon(Icons.delete_sweep),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
body: _loading
|
||||||
|
? const Center(child: CircularProgressIndicator())
|
||||||
|
: ListView(
|
||||||
|
padding: const EdgeInsets.all(12),
|
||||||
|
children: [
|
||||||
|
_buildPendingSection(),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
_buildTestSnoozeSection(), // Add the test snooze section
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
_buildLogSection(pendingIds),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildPendingSection() {
|
||||||
|
return Card(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(12),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text('Pending (${_pending.length})', style: Theme.of(context).textTheme.titleMedium),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
if (_pending.isEmpty)
|
||||||
|
const Text('No pending notifications'),
|
||||||
|
for (final p in _pending) _buildPendingTile(p),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildTestSnoozeSection() {
|
||||||
|
return Card(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(12),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text('Test Snooze', style: Theme.of(context).textTheme.titleMedium),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
ElevatedButton(
|
||||||
|
onPressed: () async {
|
||||||
|
// Trigger a test snooze notification with snooze actions
|
||||||
|
await SimpleNotificationService.instance.showInstant(
|
||||||
|
title: 'Test Snooze Notification',
|
||||||
|
body: 'This is a test notification for snooze.',
|
||||||
|
payload: jsonEncode({
|
||||||
|
"type": "single",
|
||||||
|
"id": 1, // Use a dummy ID for testing
|
||||||
|
"meta": {"kind": "daily"} // Simulate a daily notification
|
||||||
|
}),
|
||||||
|
includeSnoozeActions: true, // Include snooze actions
|
||||||
|
isSingle: true, // This is a single notification
|
||||||
|
);
|
||||||
|
if (!mounted) return;
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
const SnackBar(content: Text('Test snooze notification sent!')),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
child: const Text('Send Test Snooze Notification'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildPendingTile(PendingNotificationRequest p) {
|
||||||
|
final kind = _extractKindFromPayload(p.payload);
|
||||||
|
final singleId = _extractSingleIdFromPayload(p.payload);
|
||||||
|
final groupTime = _extractGroupTimeFromPayload(p.payload);
|
||||||
|
final schedAt = _estimateScheduledAtFromPayload(p.payload);
|
||||||
|
|
||||||
|
final forStr = singleId != null
|
||||||
|
? (_supplementNameCache[singleId] != null
|
||||||
|
? '${_supplementNameCache[singleId]} (id=$singleId)'
|
||||||
|
: 'Supplement id=$singleId')
|
||||||
|
: (groupTime != null ? 'Time $groupTime' : 'unknown');
|
||||||
|
|
||||||
|
// Build a clearer subtitle with scheduled time prominently displayed
|
||||||
|
String subtitle = 'Kind: $kind • For: $forStr';
|
||||||
|
if (schedAt != null) {
|
||||||
|
final now = DateTime.now();
|
||||||
|
final diff = schedAt.difference(now);
|
||||||
|
String whenStr;
|
||||||
|
if (diff.isNegative) {
|
||||||
|
whenStr = 'Overdue (${schedAt.toLocal().toString().substring(0, 16)})';
|
||||||
|
} else if (diff.inDays > 0) {
|
||||||
|
whenStr = 'In ${diff.inDays}d ${diff.inHours % 24}h (${schedAt.toLocal().toString().substring(0, 16)})';
|
||||||
|
} else if (diff.inHours > 0) {
|
||||||
|
whenStr = 'In ${diff.inHours}h ${diff.inMinutes % 60}m (${schedAt.toLocal().toString().substring(11, 16)})';
|
||||||
|
} else if (diff.inMinutes > 0) {
|
||||||
|
whenStr = 'In ${diff.inMinutes}m (${schedAt.toLocal().toString().substring(11, 16)})';
|
||||||
|
} else {
|
||||||
|
whenStr = 'Very soon (${schedAt.toLocal().toString().substring(11, 16)})';
|
||||||
|
}
|
||||||
|
subtitle = '$subtitle\n🕒 $whenStr';
|
||||||
|
}
|
||||||
|
// Removed the "else" block that displayed "Schedule time unknown"
|
||||||
|
|
||||||
|
return ListTile(
|
||||||
|
dense: true,
|
||||||
|
title: Text('ID ${p.id} — ${p.title ?? "(no title)"}'),
|
||||||
|
subtitle: Text(subtitle),
|
||||||
|
trailing: Wrap(
|
||||||
|
spacing: 4,
|
||||||
|
children: [
|
||||||
|
IconButton(
|
||||||
|
tooltip: 'Copy payload',
|
||||||
|
icon: const Icon(Icons.copy),
|
||||||
|
onPressed: () => _copyToClipboard(p.payload ?? ''),
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
tooltip: 'Cancel',
|
||||||
|
icon: const Icon(Icons.cancel),
|
||||||
|
onPressed: () => _cancelId(p.id),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildLogSection(Set<int> pendingIds) {
|
||||||
|
return Card(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(12),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text('Schedule Log (${_logEntries.length})', style: Theme.of(context).textTheme.titleMedium),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
if (_logEntries.isEmpty)
|
||||||
|
const Text('No log entries'),
|
||||||
|
for (final e in _logEntries) _buildLogTile(e, pendingIds),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildLogTile(NotificationLogEntry e, Set<int> pendingIds) {
|
||||||
|
final inQueue = pendingIds.contains(e.id);
|
||||||
|
String forStr = 'unknown';
|
||||||
|
if (e.type == 'single') {
|
||||||
|
if (e.singleId != null) {
|
||||||
|
final name = _supplementNameCache[e.singleId!];
|
||||||
|
forStr = name != null ? '$name (id=${e.singleId})' : 'id=${e.singleId}';
|
||||||
|
}
|
||||||
|
} else if (e.type == 'group') {
|
||||||
|
if (e.timeKey != null) {
|
||||||
|
forStr = 'Time ${e.timeKey}';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final scheduledAt = DateTime.fromMillisecondsSinceEpoch(e.whenEpochMs).toLocal();
|
||||||
|
final createdAt = DateTime.fromMillisecondsSinceEpoch(e.createdAtEpochMs).toLocal();
|
||||||
|
|
||||||
|
// Format times more clearly
|
||||||
|
final scheduledStr = '${scheduledAt.toString().substring(0, 16)}';
|
||||||
|
final createdStr = '${createdAt.toString().substring(0, 16)}';
|
||||||
|
|
||||||
|
// Show status and timing info
|
||||||
|
final statusStr = inQueue ? '🟡 Pending' : '✅ Completed/Canceled';
|
||||||
|
|
||||||
|
return ListTile(
|
||||||
|
dense: true,
|
||||||
|
leading: Icon(inQueue ? Icons.pending : Icons.check, color: inQueue ? Colors.amber : Colors.green),
|
||||||
|
title: Text('[${e.kind}] ${e.title} (ID ${e.id})'),
|
||||||
|
subtitle: Text('$statusStr • Type: ${e.type} • For: $forStr\n🕒 Scheduled: $scheduledStr\n📝 Created: $createdStr'),
|
||||||
|
trailing: Wrap(
|
||||||
|
spacing: 4,
|
||||||
|
children: [
|
||||||
|
IconButton(
|
||||||
|
tooltip: 'Copy payload',
|
||||||
|
icon: const Icon(Icons.copy),
|
||||||
|
onPressed: () => _copyToClipboard(e.payload),
|
||||||
|
),
|
||||||
|
if (inQueue)
|
||||||
|
IconButton(
|
||||||
|
tooltip: 'Cancel',
|
||||||
|
icon: const Icon(Icons.cancel),
|
||||||
|
onPressed: () => _cancelId(e.id),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,8 +2,8 @@ import 'package:flutter/material.dart';
|
|||||||
import 'package:intl/intl.dart';
|
import 'package:intl/intl.dart';
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
|
|
||||||
|
import '../providers/settings_provider.dart';
|
||||||
import '../providers/supplement_provider.dart';
|
import '../providers/supplement_provider.dart';
|
||||||
import '../providers/sync_provider.dart';
|
|
||||||
|
|
||||||
class HistoryScreen extends StatefulWidget {
|
class HistoryScreen extends StatefulWidget {
|
||||||
const HistoryScreen({super.key});
|
const HistoryScreen({super.key});
|
||||||
@@ -32,32 +32,6 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
|||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
title: const Text('Intake History'),
|
title: const Text('Intake History'),
|
||||||
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
|
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
|
||||||
actions: [
|
|
||||||
Consumer<SyncProvider>(
|
|
||||||
builder: (context, syncProvider, child) {
|
|
||||||
if (!syncProvider.isConfigured) {
|
|
||||||
return const SizedBox.shrink();
|
|
||||||
}
|
|
||||||
|
|
||||||
return IconButton(
|
|
||||||
icon: syncProvider.isSyncing
|
|
||||||
? const SizedBox(
|
|
||||||
width: 20,
|
|
||||||
height: 20,
|
|
||||||
child: CircularProgressIndicator(strokeWidth: 2),
|
|
||||||
)
|
|
||||||
: syncProvider.status.name == 'success' &&
|
|
||||||
DateTime.now().difference(syncProvider.lastSyncTime ?? DateTime.now()).inSeconds < 5
|
|
||||||
? const Icon(Icons.check, color: Colors.green)
|
|
||||||
: const Icon(Icons.sync),
|
|
||||||
onPressed: syncProvider.isSyncing ? null : () {
|
|
||||||
syncProvider.performManualSync();
|
|
||||||
},
|
|
||||||
tooltip: syncProvider.isSyncing ? 'Syncing...' : 'Force Sync',
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
),
|
||||||
body: _buildCalendarView(),
|
body: _buildCalendarView(),
|
||||||
);
|
);
|
||||||
@@ -152,15 +126,19 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
|||||||
Expanded(
|
Expanded(
|
||||||
flex: 3,
|
flex: 3,
|
||||||
child: Container(
|
child: Container(
|
||||||
margin: const EdgeInsets.fromLTRB(0, 16, 16, 16),
|
// add a bit more horizontal spacing between calendar and card
|
||||||
|
margin: const EdgeInsets.fromLTRB(8, 16, 16, 16),
|
||||||
|
child: SingleChildScrollView(
|
||||||
child: _buildSelectedDayDetails(groupedIntakes),
|
child: _buildSelectedDayDetails(groupedIntakes),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
// Mobile layout: vertical stack
|
// Mobile layout: vertical stack
|
||||||
return Column(
|
return SingleChildScrollView(
|
||||||
|
child: Column(
|
||||||
children: [
|
children: [
|
||||||
// Calendar
|
// Calendar
|
||||||
Container(
|
Container(
|
||||||
@@ -169,10 +147,12 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
|||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
// Selected day details
|
// Selected day details
|
||||||
Expanded(
|
Container(
|
||||||
|
margin: const EdgeInsets.symmetric(horizontal: 16),
|
||||||
child: _buildSelectedDayDetails(groupedIntakes),
|
child: _buildSelectedDayDetails(groupedIntakes),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -506,16 +486,140 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
Expanded(
|
Padding(
|
||||||
child: ListView.builder(
|
|
||||||
padding: EdgeInsets.all(isWideScreen ? 20 : 16),
|
padding: EdgeInsets.all(isWideScreen ? 20 : 16),
|
||||||
itemCount: dayIntakes.length,
|
child: Builder(
|
||||||
itemBuilder: (context, index) {
|
builder: (context) {
|
||||||
final intake = dayIntakes[index];
|
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: [
|
||||||
|
Container(
|
||||||
|
padding: const EdgeInsets.all(8),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: color.withOpacity(0.2),
|
||||||
|
shape: BoxShape.circle,
|
||||||
|
),
|
||||||
|
child: Icon(
|
||||||
|
icon,
|
||||||
|
size: 20,
|
||||||
|
color: color,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
title,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 18,
|
||||||
|
fontWeight: FontWeight.bold,
|
||||||
|
color: color,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (range != null) ...[
|
||||||
|
Text(
|
||||||
|
'($range)',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
fontWeight: FontWeight.w500,
|
||||||
|
color: color.withOpacity(0.8),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// 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 takenAt = DateTime.parse(intake['takenAt']);
|
||||||
final units = (intake['unitsTaken'] as num?)?.toDouble() ?? 1.0;
|
final units = (intake['unitsTaken'] as num?)?.toDouble() ?? 1.0;
|
||||||
|
final currentCategory = timeCategory(takenAt);
|
||||||
return Card(
|
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),
|
margin: const EdgeInsets.only(bottom: 12),
|
||||||
elevation: 2,
|
elevation: 2,
|
||||||
child: Padding(
|
child: Padding(
|
||||||
@@ -578,6 +682,12 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: children,
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
|
|
||||||
import '../providers/supplement_provider.dart';
|
import '../providers/supplement_provider.dart';
|
||||||
import '../providers/settings_provider.dart';
|
|
||||||
import 'supplements_list_screen.dart';
|
|
||||||
import 'history_screen.dart';
|
|
||||||
import 'add_supplement_screen.dart';
|
import 'add_supplement_screen.dart';
|
||||||
|
import 'history_screen.dart';
|
||||||
import 'settings_screen.dart';
|
import 'settings_screen.dart';
|
||||||
|
import 'supplements_list_screen.dart';
|
||||||
|
|
||||||
class HomeScreen extends StatefulWidget {
|
class HomeScreen extends StatefulWidget {
|
||||||
const HomeScreen({super.key});
|
const HomeScreen({super.key});
|
||||||
@@ -28,45 +28,10 @@ class _HomeScreenState extends State<HomeScreen> {
|
|||||||
super.initState();
|
super.initState();
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
context.read<SupplementProvider>().initialize();
|
context.read<SupplementProvider>().initialize();
|
||||||
_startPersistentReminderCheck();
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
void _startPersistentReminderCheck() {
|
// Persistent reminder checks removed
|
||||||
// Check immediately and then every 3 minutes (faster than any retry interval)
|
|
||||||
_checkPersistentReminders();
|
|
||||||
|
|
||||||
// Set up periodic checking every 3 minutes to ensure we catch all retry intervals
|
|
||||||
Future.doWhile(() async {
|
|
||||||
await Future.delayed(const Duration(minutes: 3));
|
|
||||||
if (mounted) {
|
|
||||||
await _checkPersistentReminders();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _checkPersistentReminders() async {
|
|
||||||
if (!mounted) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
print('📱 === HOME SCREEN: Checking persistent reminders ===');
|
|
||||||
final supplementProvider = context.read<SupplementProvider>();
|
|
||||||
final settingsProvider = context.read<SettingsProvider>();
|
|
||||||
|
|
||||||
print('📱 Settings: persistent=${settingsProvider.persistentReminders}, interval=${settingsProvider.reminderRetryInterval}, max=${settingsProvider.maxRetryAttempts}');
|
|
||||||
|
|
||||||
await supplementProvider.checkPersistentRemindersWithSettings(
|
|
||||||
persistentReminders: settingsProvider.persistentReminders,
|
|
||||||
reminderRetryInterval: settingsProvider.reminderRetryInterval,
|
|
||||||
maxRetryAttempts: settingsProvider.maxRetryAttempts,
|
|
||||||
);
|
|
||||||
print('📱 === HOME SCREEN: Persistent reminder check complete ===');
|
|
||||||
} catch (e) {
|
|
||||||
print('Error checking persistent reminders: $e');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
|||||||
@@ -1,823 +1,58 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
|
||||||
import 'package:provider/provider.dart';
|
|
||||||
import '../services/notification_service.dart';
|
|
||||||
import '../services/database_helper.dart';
|
|
||||||
import '../providers/settings_provider.dart';
|
|
||||||
import '../providers/supplement_provider.dart';
|
|
||||||
|
|
||||||
class PendingNotificationsScreen extends StatefulWidget {
|
/// Simple placeholder screen for pending notifications.
|
||||||
|
/// In the simplified notification setup, we no longer track or retry notifications,
|
||||||
|
/// so there is no "pending notifications" list to display.
|
||||||
|
///
|
||||||
|
/// Keep this screen minimal to avoid heavy logic and dependencies.
|
||||||
|
class PendingNotificationsScreen extends StatelessWidget {
|
||||||
const PendingNotificationsScreen({super.key});
|
const PendingNotificationsScreen({super.key});
|
||||||
|
|
||||||
@override
|
|
||||||
State<PendingNotificationsScreen> createState() => _PendingNotificationsScreenState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _PendingNotificationsScreenState extends State<PendingNotificationsScreen> {
|
|
||||||
List<PendingNotificationRequest> _pendingNotifications = [];
|
|
||||||
List<Map<String, dynamic>> _trackedNotifications = [];
|
|
||||||
bool _isLoading = true;
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
_loadNotifications();
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _loadNotifications() async {
|
|
||||||
setState(() {
|
|
||||||
_isLoading = true;
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Get settings for retry interval calculation
|
|
||||||
final settingsProvider = Provider.of<SettingsProvider>(context, listen: false);
|
|
||||||
final reminderRetryInterval = settingsProvider.reminderRetryInterval;
|
|
||||||
final maxRetryAttempts = settingsProvider.maxRetryAttempts;
|
|
||||||
|
|
||||||
// Get system pending notifications
|
|
||||||
final notificationService = NotificationService();
|
|
||||||
final systemPending = await notificationService.getPendingNotifications();
|
|
||||||
|
|
||||||
// Get tracked notifications from database (including retries)
|
|
||||||
final trackedNotifications = await DatabaseHelper.instance.getPendingNotifications();
|
|
||||||
|
|
||||||
// Create a more intelligent matching system
|
|
||||||
final allNotifications = <Map<String, dynamic>>[];
|
|
||||||
final matchedSystemIds = <int>{};
|
|
||||||
|
|
||||||
// First, try to match tracked notifications with system notifications
|
|
||||||
for (final trackedNotification in trackedNotifications) {
|
|
||||||
final scheduledTime = DateTime.parse(trackedNotification['scheduledTime']).toLocal();
|
|
||||||
final lastRetryTime = trackedNotification['lastRetryTime'] != null
|
|
||||||
? DateTime.parse(trackedNotification['lastRetryTime']).toLocal()
|
|
||||||
: null;
|
|
||||||
final retryCount = trackedNotification['retryCount'] ?? 0;
|
|
||||||
final isRetrying = trackedNotification['status'] == 'retrying';
|
|
||||||
final notificationId = trackedNotification['notificationId'] as int;
|
|
||||||
|
|
||||||
// Try to find matching system notification(s)
|
|
||||||
final matchingSystemNotifications = systemPending.where((systemNotification) {
|
|
||||||
return _isMatchingNotification(systemNotification, trackedNotification, retryCount);
|
|
||||||
}).toList();
|
|
||||||
|
|
||||||
// Calculate next retry time if this is a retry notification
|
|
||||||
DateTime? nextRetryTime;
|
|
||||||
bool hasReachedMaxRetries = retryCount >= maxRetryAttempts;
|
|
||||||
|
|
||||||
if (isRetrying && !hasReachedMaxRetries) {
|
|
||||||
if (lastRetryTime != null) {
|
|
||||||
// Next retry is based on last retry time + interval
|
|
||||||
nextRetryTime = lastRetryTime.add(Duration(minutes: reminderRetryInterval));
|
|
||||||
} else {
|
|
||||||
// First retry is based on original scheduled time + interval
|
|
||||||
nextRetryTime = scheduledTime.add(Duration(minutes: reminderRetryInterval));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create the notification entry
|
|
||||||
final notificationEntry = {
|
|
||||||
'id': notificationId,
|
|
||||||
'title': 'Time for ${trackedNotification['supplementName'] ?? 'Supplement'}',
|
|
||||||
'body': 'Take your supplement',
|
|
||||||
'scheduledTime': scheduledTime,
|
|
||||||
'nextRetryTime': nextRetryTime,
|
|
||||||
'lastRetryTime': lastRetryTime,
|
|
||||||
'type': matchingSystemNotifications.isNotEmpty ? 'matched' : 'tracked_only',
|
|
||||||
'status': trackedNotification['status'],
|
|
||||||
'isRetry': isRetrying,
|
|
||||||
'retryCount': retryCount,
|
|
||||||
'hasReachedMaxRetries': hasReachedMaxRetries,
|
|
||||||
'maxRetryAttempts': maxRetryAttempts,
|
|
||||||
'supplementName': trackedNotification['supplementName'],
|
|
||||||
'supplementId': trackedNotification['supplementId'],
|
|
||||||
'systemNotificationCount': matchingSystemNotifications.length,
|
|
||||||
};
|
|
||||||
|
|
||||||
allNotifications.add(notificationEntry);
|
|
||||||
|
|
||||||
// Mark these system notifications as matched
|
|
||||||
for (final systemNotification in matchingSystemNotifications) {
|
|
||||||
matchedSystemIds.add(systemNotification.id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add unmatched system notifications
|
|
||||||
for (final systemNotification in systemPending) {
|
|
||||||
if (!matchedSystemIds.contains(systemNotification.id)) {
|
|
||||||
allNotifications.add({
|
|
||||||
'id': systemNotification.id,
|
|
||||||
'title': systemNotification.title ?? 'System Notification',
|
|
||||||
'body': systemNotification.body ?? '',
|
|
||||||
'scheduledTime': DateTime.now(), // PendingNotificationRequest doesn't have scheduledTime
|
|
||||||
'type': 'system_only',
|
|
||||||
'isRetry': false,
|
|
||||||
'retryCount': 0,
|
|
||||||
'hasReachedMaxRetries': false,
|
|
||||||
'maxRetryAttempts': maxRetryAttempts,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sort by scheduled time (soonest first)
|
|
||||||
allNotifications.sort((a, b) {
|
|
||||||
final timeA = a['scheduledTime'] as DateTime;
|
|
||||||
final timeB = b['scheduledTime'] as DateTime;
|
|
||||||
return timeA.compareTo(timeB);
|
|
||||||
});
|
|
||||||
|
|
||||||
setState(() {
|
|
||||||
_pendingNotifications = systemPending;
|
|
||||||
_trackedNotifications = trackedNotifications;
|
|
||||||
_isLoading = false;
|
|
||||||
});
|
|
||||||
} catch (e) {
|
|
||||||
print('Error loading notifications: $e');
|
|
||||||
setState(() {
|
|
||||||
_isLoading = false;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _showCleanupDialog() async {
|
|
||||||
final result = await showDialog<String>(
|
|
||||||
context: context,
|
|
||||||
builder: (BuildContext context) {
|
|
||||||
return AlertDialog(
|
|
||||||
title: const Text('Cleanup Old Notifications'),
|
|
||||||
content: const Text(
|
|
||||||
'This will help clean up old or duplicate notifications:\n\n'
|
|
||||||
'• Clear stale system notifications\n'
|
|
||||||
'• Remove very old tracked notifications (>24h overdue)\n'
|
|
||||||
'• Reschedule fresh notifications for active supplements\n\n'
|
|
||||||
'Choose an option:',
|
|
||||||
),
|
|
||||||
actions: [
|
|
||||||
TextButton(
|
|
||||||
onPressed: () => Navigator.of(context).pop('cancel'),
|
|
||||||
child: const Text('Cancel'),
|
|
||||||
),
|
|
||||||
TextButton(
|
|
||||||
onPressed: () => Navigator.of(context).pop('clear_old'),
|
|
||||||
child: const Text('Clear Old Only'),
|
|
||||||
),
|
|
||||||
TextButton(
|
|
||||||
onPressed: () => Navigator.of(context).pop('clear_all'),
|
|
||||||
child: const Text('Clear All & Reschedule'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
if (result != null && result != 'cancel') {
|
|
||||||
await _performCleanup(result);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _performCleanup(String action) async {
|
|
||||||
try {
|
|
||||||
// Show loading indicator
|
|
||||||
if (mounted) {
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
const SnackBar(
|
|
||||||
content: Text('Cleaning up notifications...'),
|
|
||||||
duration: Duration(seconds: 2),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
final notificationService = NotificationService();
|
|
||||||
|
|
||||||
if (action == 'clear_all') {
|
|
||||||
// Clear all notifications and reschedule fresh ones
|
|
||||||
await notificationService.cancelAllReminders();
|
|
||||||
await DatabaseHelper.instance.cleanupOldNotificationTracking();
|
|
||||||
|
|
||||||
// Reschedule notifications for all active supplements
|
|
||||||
final supplementProvider = Provider.of<SupplementProvider>(context, listen: false);
|
|
||||||
await supplementProvider.rescheduleAllNotifications();
|
|
||||||
|
|
||||||
if (mounted) {
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
const SnackBar(
|
|
||||||
content: Text('All notifications cleared and rescheduled!'),
|
|
||||||
backgroundColor: Colors.green,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} else if (action == 'clear_old') {
|
|
||||||
// Clear only very old notifications (>24 hours overdue)
|
|
||||||
await _clearOldNotifications();
|
|
||||||
|
|
||||||
if (mounted) {
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
const SnackBar(
|
|
||||||
content: Text('Old notifications cleared!'),
|
|
||||||
backgroundColor: Colors.orange,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Refresh the list
|
|
||||||
await _loadNotifications();
|
|
||||||
} catch (e) {
|
|
||||||
if (mounted) {
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
SnackBar(
|
|
||||||
content: Text('Error during cleanup: $e'),
|
|
||||||
backgroundColor: Colors.red,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _clearOldNotifications() async {
|
|
||||||
final now = DateTime.now();
|
|
||||||
final cutoff = now.subtract(const Duration(hours: 24));
|
|
||||||
|
|
||||||
// Clear very old tracked notifications
|
|
||||||
final db = await DatabaseHelper.instance.database;
|
|
||||||
await db.delete(
|
|
||||||
'notification_tracking',
|
|
||||||
where: 'scheduledTime < ? AND status IN (?, ?)',
|
|
||||||
whereArgs: [cutoff.toIso8601String(), 'pending', 'retrying'],
|
|
||||||
);
|
|
||||||
|
|
||||||
// Note: We can't selectively clear system notifications as we don't have their scheduled times
|
|
||||||
// This is a limitation of the flutter_local_notifications plugin
|
|
||||||
}
|
|
||||||
|
|
||||||
bool _isMatchingNotification(PendingNotificationRequest systemNotification, Map<String, dynamic> trackedNotification, int retryCount) {
|
|
||||||
final trackedId = trackedNotification['notificationId'] as int;
|
|
||||||
final supplementId = trackedNotification['supplementId'] as int;
|
|
||||||
|
|
||||||
// Check for exact ID match (original notification)
|
|
||||||
if (systemNotification.id == trackedId) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check for retry notification IDs (200000 + original_id * 10 + retry_attempt)
|
|
||||||
for (int attempt = 1; attempt <= retryCount; attempt++) {
|
|
||||||
final retryId = 200000 + (trackedId * 10) + attempt;
|
|
||||||
if (systemNotification.id == retryId) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check for snooze notification IDs (supplementId * 1000 + minutes)
|
|
||||||
// Common snooze intervals: 5, 10, 15, 30 minutes
|
|
||||||
final snoozeIds = [5, 10, 15, 30].map((minutes) => supplementId * 1000 + minutes);
|
|
||||||
if (snoozeIds.contains(systemNotification.id)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if it's within the supplement's notification ID range (supplementId * 100 + reminderIndex)
|
|
||||||
final baseId = supplementId * 100;
|
|
||||||
if (systemNotification.id >= baseId && systemNotification.id < baseId + 10) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
Color _getTypeColor(String type) {
|
|
||||||
switch (type) {
|
|
||||||
case 'matched':
|
|
||||||
return Colors.green;
|
|
||||||
case 'tracked_only':
|
|
||||||
return Colors.orange;
|
|
||||||
case 'system_only':
|
|
||||||
return Colors.blue;
|
|
||||||
default:
|
|
||||||
return Colors.grey;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Color _getTypeDarkColor(String type) {
|
|
||||||
switch (type) {
|
|
||||||
case 'matched':
|
|
||||||
return Colors.green.shade700;
|
|
||||||
case 'tracked_only':
|
|
||||||
return Colors.orange.shade700;
|
|
||||||
case 'system_only':
|
|
||||||
return Colors.blue.shade700;
|
|
||||||
default:
|
|
||||||
return Colors.grey.shade700;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String _getTypeLabel(String type, Map<String, dynamic> notification) {
|
|
||||||
final systemCount = notification['systemNotificationCount'] as int? ?? 0;
|
|
||||||
|
|
||||||
switch (type) {
|
|
||||||
case 'matched':
|
|
||||||
return systemCount > 1 ? 'Matched' : 'Synced';
|
|
||||||
case 'tracked_only':
|
|
||||||
return 'Tracking Only';
|
|
||||||
case 'system_only':
|
|
||||||
return 'System Only';
|
|
||||||
default:
|
|
||||||
return 'Unknown';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
title: const Text('Pending Notifications'),
|
title: const Text('Pending Notifications'),
|
||||||
actions: [
|
|
||||||
IconButton(
|
|
||||||
icon: const Icon(Icons.cleaning_services),
|
|
||||||
onPressed: _showCleanupDialog,
|
|
||||||
tooltip: 'Cleanup old notifications',
|
|
||||||
),
|
),
|
||||||
IconButton(
|
body: Center(
|
||||||
icon: const Icon(Icons.refresh),
|
|
||||||
onPressed: _loadNotifications,
|
|
||||||
tooltip: 'Refresh',
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
body: _isLoading
|
|
||||||
? const Center(child: CircularProgressIndicator())
|
|
||||||
: RefreshIndicator(
|
|
||||||
onRefresh: _loadNotifications,
|
|
||||||
child: _buildNotificationsList(),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildNotificationsList() {
|
|
||||||
if (_pendingNotifications.isEmpty && _trackedNotifications.isEmpty) {
|
|
||||||
return const Center(
|
|
||||||
child: Column(
|
|
||||||
mainAxisAlignment: MainAxisAlignment.center,
|
|
||||||
children: [
|
|
||||||
Icon(
|
|
||||||
Icons.notifications_off,
|
|
||||||
size: 64,
|
|
||||||
color: Colors.grey,
|
|
||||||
),
|
|
||||||
SizedBox(height: 16),
|
|
||||||
Text(
|
|
||||||
'No pending notifications',
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 18,
|
|
||||||
color: Colors.grey,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
SizedBox(height: 8),
|
|
||||||
Text(
|
|
||||||
'All caught up!',
|
|
||||||
style: TextStyle(
|
|
||||||
color: Colors.grey,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get settings for retry interval calculation
|
|
||||||
final settingsProvider = Provider.of<SettingsProvider>(context, listen: false);
|
|
||||||
final reminderRetryInterval = settingsProvider.reminderRetryInterval;
|
|
||||||
final maxRetryAttempts = settingsProvider.maxRetryAttempts;
|
|
||||||
|
|
||||||
// Create a more intelligent matching system
|
|
||||||
final allNotifications = <Map<String, dynamic>>[];
|
|
||||||
final matchedSystemIds = <int>{};
|
|
||||||
|
|
||||||
// First, try to match tracked notifications with system notifications
|
|
||||||
for (final trackedNotification in _trackedNotifications) {
|
|
||||||
final scheduledTime = DateTime.parse(trackedNotification['scheduledTime']).toLocal();
|
|
||||||
final lastRetryTime = trackedNotification['lastRetryTime'] != null
|
|
||||||
? DateTime.parse(trackedNotification['lastRetryTime']).toLocal()
|
|
||||||
: null;
|
|
||||||
final retryCount = trackedNotification['retryCount'] ?? 0;
|
|
||||||
final isRetrying = trackedNotification['status'] == 'retrying';
|
|
||||||
final notificationId = trackedNotification['notificationId'] as int;
|
|
||||||
|
|
||||||
// Try to find matching system notification(s)
|
|
||||||
final matchingSystemNotifications = _pendingNotifications.where((systemNotification) {
|
|
||||||
return _isMatchingNotification(systemNotification, trackedNotification, retryCount);
|
|
||||||
}).toList();
|
|
||||||
|
|
||||||
// Calculate next retry time if this is a retry notification
|
|
||||||
DateTime? nextRetryTime;
|
|
||||||
bool hasReachedMaxRetries = retryCount >= maxRetryAttempts;
|
|
||||||
|
|
||||||
if (isRetrying && !hasReachedMaxRetries) {
|
|
||||||
if (lastRetryTime != null) {
|
|
||||||
// Next retry is based on last retry time + interval
|
|
||||||
nextRetryTime = lastRetryTime.add(Duration(minutes: reminderRetryInterval));
|
|
||||||
} else {
|
|
||||||
// First retry is based on original scheduled time + interval
|
|
||||||
nextRetryTime = scheduledTime.add(Duration(minutes: reminderRetryInterval));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create the notification entry
|
|
||||||
final notificationEntry = {
|
|
||||||
'id': notificationId,
|
|
||||||
'title': 'Time for ${trackedNotification['supplementName'] ?? 'Supplement'}',
|
|
||||||
'body': 'Take your supplement',
|
|
||||||
'scheduledTime': scheduledTime,
|
|
||||||
'nextRetryTime': nextRetryTime,
|
|
||||||
'lastRetryTime': lastRetryTime,
|
|
||||||
'type': matchingSystemNotifications.isNotEmpty ? 'matched' : 'tracked_only',
|
|
||||||
'status': trackedNotification['status'],
|
|
||||||
'isRetry': isRetrying,
|
|
||||||
'retryCount': retryCount,
|
|
||||||
'hasReachedMaxRetries': hasReachedMaxRetries,
|
|
||||||
'maxRetryAttempts': maxRetryAttempts,
|
|
||||||
'supplementName': trackedNotification['supplementName'],
|
|
||||||
'supplementId': trackedNotification['supplementId'],
|
|
||||||
'systemNotificationCount': matchingSystemNotifications.length,
|
|
||||||
};
|
|
||||||
|
|
||||||
allNotifications.add(notificationEntry);
|
|
||||||
|
|
||||||
// Mark these system notifications as matched
|
|
||||||
for (final systemNotification in matchingSystemNotifications) {
|
|
||||||
matchedSystemIds.add(systemNotification.id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add unmatched system notifications
|
|
||||||
for (final systemNotification in _pendingNotifications) {
|
|
||||||
if (!matchedSystemIds.contains(systemNotification.id)) {
|
|
||||||
allNotifications.add({
|
|
||||||
'id': systemNotification.id,
|
|
||||||
'title': systemNotification.title ?? 'System Notification',
|
|
||||||
'body': systemNotification.body ?? '',
|
|
||||||
'scheduledTime': DateTime.now(), // PendingNotificationRequest doesn't have scheduledTime
|
|
||||||
'type': 'system_only',
|
|
||||||
'isRetry': false,
|
|
||||||
'retryCount': 0,
|
|
||||||
'hasReachedMaxRetries': false,
|
|
||||||
'maxRetryAttempts': maxRetryAttempts,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sort by scheduled time (soonest first)
|
|
||||||
allNotifications.sort((a, b) {
|
|
||||||
final timeA = a['scheduledTime'] as DateTime;
|
|
||||||
final timeB = b['scheduledTime'] as DateTime;
|
|
||||||
return timeA.compareTo(timeB);
|
|
||||||
});
|
|
||||||
|
|
||||||
return ListView.builder(
|
|
||||||
padding: const EdgeInsets.all(16),
|
|
||||||
itemCount: allNotifications.length,
|
|
||||||
itemBuilder: (context, index) {
|
|
||||||
final notification = allNotifications[index];
|
|
||||||
return _buildNotificationCard(notification);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildNotificationCard(Map<String, dynamic> notification) {
|
|
||||||
final scheduledTime = notification['scheduledTime'] as DateTime;
|
|
||||||
final nextRetryTime = notification['nextRetryTime'] as DateTime?;
|
|
||||||
final lastRetryTime = notification['lastRetryTime'] as DateTime?;
|
|
||||||
final now = DateTime.now();
|
|
||||||
final isOverdue = scheduledTime.isBefore(now);
|
|
||||||
final isRetry = notification['isRetry'] as bool;
|
|
||||||
final retryCount = notification['retryCount'] as int;
|
|
||||||
final hasReachedMaxRetries = notification['hasReachedMaxRetries'] as bool? ?? false;
|
|
||||||
final maxRetryAttempts = notification['maxRetryAttempts'] as int? ?? 3;
|
|
||||||
final type = notification['type'] as String;
|
|
||||||
|
|
||||||
// Determine which time to show and calculate time text
|
|
||||||
DateTime displayTime = scheduledTime;
|
|
||||||
String timePrefix = '';
|
|
||||||
bool showAsNextRetry = false;
|
|
||||||
String timeText = '';
|
|
||||||
|
|
||||||
if (isRetry && nextRetryTime != null && !hasReachedMaxRetries) {
|
|
||||||
// For retry notifications that haven't reached max retries, show next retry time
|
|
||||||
final timeDifference = nextRetryTime.difference(now);
|
|
||||||
if (timeDifference.inSeconds.abs() < 30) {
|
|
||||||
// If within 30 seconds, show "due now"
|
|
||||||
displayTime = nextRetryTime;
|
|
||||||
timePrefix = 'Next retry: ';
|
|
||||||
showAsNextRetry = true;
|
|
||||||
timeText = 'due now';
|
|
||||||
} else if (nextRetryTime.isAfter(now)) {
|
|
||||||
displayTime = nextRetryTime;
|
|
||||||
timePrefix = 'Next retry: ';
|
|
||||||
showAsNextRetry = true;
|
|
||||||
} else {
|
|
||||||
// If next retry time has passed, show it's overdue for retry
|
|
||||||
displayTime = nextRetryTime;
|
|
||||||
timePrefix = 'Retry overdue: ';
|
|
||||||
showAsNextRetry = true;
|
|
||||||
}
|
|
||||||
} else if (isRetry && hasReachedMaxRetries) {
|
|
||||||
// For notifications that have reached max retries, don't show next retry time
|
|
||||||
showAsNextRetry = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Calculate time text if not already set
|
|
||||||
if (timeText.isEmpty) {
|
|
||||||
final isDisplayTimeOverdue = displayTime.isBefore(now);
|
|
||||||
final timeUntil = displayTime.difference(now);
|
|
||||||
|
|
||||||
if (isDisplayTimeOverdue) {
|
|
||||||
final overdue = now.difference(displayTime);
|
|
||||||
if (overdue.inDays > 0) {
|
|
||||||
timeText = 'Overdue by ${overdue.inDays}d ${overdue.inHours % 24}h';
|
|
||||||
} else if (overdue.inHours > 0) {
|
|
||||||
timeText = 'Overdue by ${overdue.inHours}h ${overdue.inMinutes % 60}m';
|
|
||||||
} else if (overdue.inMinutes > 0) {
|
|
||||||
timeText = 'Overdue by ${overdue.inMinutes}m';
|
|
||||||
} else {
|
|
||||||
timeText = 'Overdue by ${overdue.inSeconds}s';
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (timeUntil.inDays > 0) {
|
|
||||||
timeText = 'In ${timeUntil.inDays}d ${timeUntil.inHours % 24}h';
|
|
||||||
} else if (timeUntil.inHours > 0) {
|
|
||||||
timeText = 'In ${timeUntil.inHours}h ${timeUntil.inMinutes % 60}m';
|
|
||||||
} else if (timeUntil.inMinutes > 0) {
|
|
||||||
timeText = 'In ${timeUntil.inMinutes}m';
|
|
||||||
} else {
|
|
||||||
timeText = 'In ${timeUntil.inSeconds}s';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Determine if display time is overdue (needed for icon colors later)
|
|
||||||
final isDisplayTimeOverdue = displayTime.isBefore(now);
|
|
||||||
|
|
||||||
return Card(
|
|
||||||
margin: const EdgeInsets.only(bottom: 12),
|
|
||||||
child: Padding(
|
child: Padding(
|
||||||
padding: const EdgeInsets.all(16),
|
padding: const EdgeInsets.all(24),
|
||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Text(
|
|
||||||
notification['title'] ?? 'Notification',
|
|
||||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
|
||||||
fontWeight: FontWeight.bold,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
if (notification['body'] != null) ...[
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
Text(
|
|
||||||
notification['body'],
|
|
||||||
style: Theme.of(context).textTheme.bodyMedium,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.end,
|
|
||||||
children: [
|
|
||||||
if (isRetry) ...[
|
|
||||||
Container(
|
|
||||||
padding: const EdgeInsets.symmetric(
|
|
||||||
horizontal: 8,
|
|
||||||
vertical: 4,
|
|
||||||
),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: hasReachedMaxRetries
|
|
||||||
? Colors.red.withOpacity(0.2)
|
|
||||||
: Colors.orange.withOpacity(0.2),
|
|
||||||
borderRadius: BorderRadius.circular(12),
|
|
||||||
border: Border.all(
|
|
||||||
color: hasReachedMaxRetries
|
|
||||||
? Colors.red.withOpacity(0.5)
|
|
||||||
: Colors.orange.withOpacity(0.5),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
child: Text(
|
|
||||||
hasReachedMaxRetries
|
|
||||||
? 'Max retries ($retryCount/$maxRetryAttempts)'
|
|
||||||
: 'Retry #$retryCount',
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 12,
|
|
||||||
color: hasReachedMaxRetries
|
|
||||||
? Colors.red.shade700
|
|
||||||
: Colors.orange.shade700,
|
|
||||||
fontWeight: FontWeight.bold,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
],
|
|
||||||
Container(
|
|
||||||
padding: const EdgeInsets.symmetric(
|
|
||||||
horizontal: 8,
|
|
||||||
vertical: 4,
|
|
||||||
),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: _getTypeColor(type).withOpacity(0.2),
|
|
||||||
borderRadius: BorderRadius.circular(12),
|
|
||||||
border: Border.all(
|
|
||||||
color: _getTypeColor(type).withOpacity(0.5),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
child: Row(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: [
|
|
||||||
Text(
|
|
||||||
_getTypeLabel(type, notification),
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 12,
|
|
||||||
color: _getTypeDarkColor(type),
|
|
||||||
fontWeight: FontWeight.bold,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
if (type == 'matched' && (notification['systemNotificationCount'] as int? ?? 0) > 1) ...[
|
|
||||||
const SizedBox(width: 4),
|
|
||||||
Container(
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Colors.white.withOpacity(0.8),
|
|
||||||
borderRadius: BorderRadius.circular(8),
|
|
||||||
),
|
|
||||||
child: Text(
|
|
||||||
'${notification['systemNotificationCount']}',
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 10,
|
|
||||||
color: _getTypeDarkColor(type),
|
|
||||||
fontWeight: FontWeight.bold,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
// Show original scheduled time
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Icon(
|
|
||||||
isOverdue ? Icons.schedule_outlined : Icons.access_time,
|
|
||||||
size: 16,
|
|
||||||
color: isOverdue ? Colors.red : Colors.grey,
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Text(
|
|
||||||
'Scheduled: ${_formatTime(scheduledTime)}',
|
|
||||||
style: TextStyle(
|
|
||||||
color: isOverdue ? Colors.red : Colors.grey.shade700,
|
|
||||||
fontWeight: isOverdue ? FontWeight.bold : FontWeight.normal,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
if (isOverdue) ...[
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Text(
|
|
||||||
'(${_formatOverdueTime(scheduledTime)})',
|
|
||||||
style: TextStyle(
|
|
||||||
color: Colors.red,
|
|
||||||
fontSize: 12,
|
|
||||||
fontWeight: FontWeight.bold,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
|
||||||
// Show next retry time if applicable
|
|
||||||
if (showAsNextRetry && nextRetryTime != null) ...[
|
|
||||||
const SizedBox(height: 6),
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Icon(
|
|
||||||
isDisplayTimeOverdue ? Icons.warning_outlined : Icons.refresh,
|
|
||||||
size: 16,
|
|
||||||
color: isDisplayTimeOverdue ? Colors.red : Colors.orange,
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Text(
|
|
||||||
'${timePrefix}${_formatTime(displayTime)} • $timeText',
|
|
||||||
style: TextStyle(
|
|
||||||
color: isDisplayTimeOverdue ? Colors.red : Colors.orange.shade700,
|
|
||||||
fontWeight: FontWeight.bold,
|
|
||||||
fontSize: 13,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
],
|
|
||||||
// Show max retries reached message
|
|
||||||
if (isRetry && hasReachedMaxRetries) ...[
|
|
||||||
const SizedBox(height: 6),
|
|
||||||
Row(
|
|
||||||
children: [
|
children: [
|
||||||
const Icon(
|
const Icon(
|
||||||
Icons.block,
|
Icons.notifications_none,
|
||||||
size: 16,
|
size: 72,
|
||||||
color: Colors.red,
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Expanded(
|
|
||||||
child: Text(
|
|
||||||
'Maximum retry attempts reached. No more reminders will be sent.',
|
|
||||||
style: TextStyle(
|
|
||||||
color: Colors.red.shade700,
|
|
||||||
fontSize: 12,
|
|
||||||
fontWeight: FontWeight.bold,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
],
|
|
||||||
// Show last retry time if available
|
|
||||||
if (isRetry && lastRetryTime != null) ...[
|
|
||||||
const SizedBox(height: 6),
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
const Icon(
|
|
||||||
Icons.history,
|
|
||||||
size: 16,
|
|
||||||
color: Colors.grey,
|
color: Colors.grey,
|
||||||
),
|
),
|
||||||
const SizedBox(width: 8),
|
const SizedBox(height: 16),
|
||||||
Text(
|
Text(
|
||||||
'Last retry: ${_formatTime(lastRetryTime)}',
|
'No pending notifications UI in simple mode',
|
||||||
style: TextStyle(
|
textAlign: TextAlign.center,
|
||||||
color: Colors.grey.shade600,
|
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||||
fontSize: 12,
|
color: Colors.grey.shade800,
|
||||||
fontStyle: FontStyle.italic,
|
fontWeight: FontWeight.w600,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
|
||||||
),
|
|
||||||
],
|
|
||||||
if (type == 'tracked' && notification['supplementName'] != null) ...[
|
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
const Icon(
|
|
||||||
Icons.medication,
|
|
||||||
size: 16,
|
|
||||||
color: Colors.grey,
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Text(
|
Text(
|
||||||
notification['supplementName'],
|
'Notifications are now scheduled daily at the selected times '
|
||||||
style: TextStyle(
|
'without retries or tracking.',
|
||||||
color: Colors.grey.shade700,
|
textAlign: TextAlign.center,
|
||||||
fontStyle: FontStyle.italic,
|
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||||
|
color: Colors.grey.shade600,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
const SizedBox(height: 24),
|
||||||
|
ElevatedButton.icon(
|
||||||
|
onPressed: () => Navigator.of(context).maybePop(),
|
||||||
|
icon: const Icon(Icons.close),
|
||||||
|
label: const Text('Close'),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
String _formatTime(DateTime dateTime) {
|
|
||||||
final now = DateTime.now();
|
|
||||||
final today = DateTime(now.year, now.month, now.day);
|
|
||||||
final tomorrow = today.add(const Duration(days: 1));
|
|
||||||
final notificationDate = DateTime(dateTime.year, dateTime.month, dateTime.day);
|
|
||||||
|
|
||||||
String timeStr = '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
|
|
||||||
|
|
||||||
if (notificationDate == today) {
|
|
||||||
return 'Today $timeStr';
|
|
||||||
} else if (notificationDate == tomorrow) {
|
|
||||||
return 'Tomorrow $timeStr';
|
|
||||||
} else {
|
|
||||||
return '${dateTime.day}/${dateTime.month} $timeStr';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String _formatOverdueTime(DateTime scheduledTime) {
|
|
||||||
final now = DateTime.now();
|
|
||||||
final overdue = now.difference(scheduledTime);
|
|
||||||
|
|
||||||
if (overdue.inDays > 0) {
|
|
||||||
return '${overdue.inDays}d ${overdue.inHours % 24}h overdue';
|
|
||||||
} else if (overdue.inHours > 0) {
|
|
||||||
return '${overdue.inHours}h ${overdue.inMinutes % 60}m overdue';
|
|
||||||
} else {
|
|
||||||
return '${overdue.inMinutes}m overdue';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
|
|
||||||
import '../providers/settings_provider.dart';
|
import '../providers/settings_provider.dart';
|
||||||
import '../providers/supplement_provider.dart';
|
import 'debug_notifications_screen.dart';
|
||||||
import '../services/notification_service.dart';
|
import 'simple_sync_settings_screen.dart';
|
||||||
import 'pending_notifications_screen.dart';
|
|
||||||
import 'sync_settings_screen.dart';
|
|
||||||
|
|
||||||
class SettingsScreen extends StatelessWidget {
|
class SettingsScreen extends StatelessWidget {
|
||||||
const SettingsScreen({super.key});
|
const SettingsScreen({super.key});
|
||||||
@@ -21,6 +20,41 @@ class SettingsScreen extends StatelessWidget {
|
|||||||
return ListView(
|
return ListView(
|
||||||
padding: const EdgeInsets.all(16.0),
|
padding: const EdgeInsets.all(16.0),
|
||||||
children: [
|
children: [
|
||||||
|
// Debug section (only in debug builds)
|
||||||
|
if (kDebugMode) ...[
|
||||||
|
Card(
|
||||||
|
child: ListTile(
|
||||||
|
leading: const Icon(Icons.bug_report),
|
||||||
|
title: const Text('Debug Notifications'),
|
||||||
|
subtitle: const Text('View scheduled notifications and debug log'),
|
||||||
|
trailing: const Icon(Icons.chevron_right),
|
||||||
|
onTap: () {
|
||||||
|
Navigator.of(context).push(
|
||||||
|
MaterialPageRoute(
|
||||||
|
builder: (context) => const DebugNotificationsScreen(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
],
|
||||||
|
Card(
|
||||||
|
child: ListTile(
|
||||||
|
leading: const Icon(Icons.cloud_sync),
|
||||||
|
title: const Text('Cloud Sync'),
|
||||||
|
subtitle: const Text('Configure WebDAV sync settings'),
|
||||||
|
trailing: const Icon(Icons.chevron_right),
|
||||||
|
onTap: () {
|
||||||
|
Navigator.of(context).push(
|
||||||
|
MaterialPageRoute(
|
||||||
|
builder: (context) => const SimpleSyncSettingsScreen(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
Card(
|
Card(
|
||||||
child: Padding(
|
child: Padding(
|
||||||
padding: const EdgeInsets.all(16.0),
|
padding: const EdgeInsets.all(16.0),
|
||||||
@@ -70,21 +104,28 @@ class SettingsScreen extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
|
// Notifications
|
||||||
Card(
|
Card(
|
||||||
child: ListTile(
|
child: ListTile(
|
||||||
leading: const Icon(Icons.cloud_sync),
|
leading: const Icon(Icons.snooze),
|
||||||
title: const Text('Cloud Sync'),
|
title: const Text('Snooze duration'),
|
||||||
subtitle: const Text('Configure WebDAV sync settings'),
|
subtitle: const Text('Delay for Snooze action'),
|
||||||
trailing: const Icon(Icons.chevron_right),
|
trailing: DropdownButton<int>(
|
||||||
onTap: () {
|
value: settingsProvider.snoozeMinutes,
|
||||||
Navigator.of(context).push(
|
items: const [
|
||||||
MaterialPageRoute(
|
DropdownMenuItem(value: 5, child: Text('5 min')),
|
||||||
builder: (context) => const SyncSettingsScreen(),
|
DropdownMenuItem(value: 10, child: Text('10 min')),
|
||||||
),
|
DropdownMenuItem(value: 15, child: Text('15 min')),
|
||||||
);
|
DropdownMenuItem(value: 20, child: Text('20 min')),
|
||||||
|
],
|
||||||
|
onChanged: (value) {
|
||||||
|
if (value != null) {
|
||||||
|
settingsProvider.setSnoozeMinutes(value);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Card(
|
Card(
|
||||||
child: Padding(
|
child: Padding(
|
||||||
@@ -155,354 +196,6 @@ class SettingsScreen extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
|
||||||
Card(
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.all(16.0),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Icon(Icons.notifications_active, color: Colors.blue),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Text(
|
|
||||||
'Persistent Reminders',
|
|
||||||
style: Theme.of(context).textTheme.titleMedium,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Text(
|
|
||||||
'Configure automatic reminder retries for ignored notifications',
|
|
||||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
SwitchListTile(
|
|
||||||
title: const Text('Enable Persistent Reminders'),
|
|
||||||
subtitle: const Text('Resend notifications if ignored'),
|
|
||||||
value: settingsProvider.persistentReminders,
|
|
||||||
onChanged: (value) {
|
|
||||||
settingsProvider.setPersistentReminders(value);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
if (settingsProvider.persistentReminders) ...[
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
Text(
|
|
||||||
'Retry Interval',
|
|
||||||
style: Theme.of(context).textTheme.titleSmall,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
SegmentedButton<int>(
|
|
||||||
segments: const [
|
|
||||||
ButtonSegment(value: 5, label: Text('5 min')),
|
|
||||||
ButtonSegment(value: 10, label: Text('10 min')),
|
|
||||||
ButtonSegment(value: 15, label: Text('15 min')),
|
|
||||||
ButtonSegment(value: 30, label: Text('30 min')),
|
|
||||||
],
|
|
||||||
selected: {settingsProvider.reminderRetryInterval},
|
|
||||||
onSelectionChanged: (values) {
|
|
||||||
settingsProvider.setReminderRetryInterval(values.first);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
Text(
|
|
||||||
'Maximum Retry Attempts',
|
|
||||||
style: Theme.of(context).textTheme.titleSmall,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
SegmentedButton<int>(
|
|
||||||
segments: const [
|
|
||||||
ButtonSegment(value: 1, label: Text('1')),
|
|
||||||
ButtonSegment(value: 2, label: Text('2')),
|
|
||||||
ButtonSegment(value: 3, label: Text('3')),
|
|
||||||
ButtonSegment(value: 4, label: Text('4')),
|
|
||||||
ButtonSegment(value: 5, label: Text('5')),
|
|
||||||
],
|
|
||||||
selected: {settingsProvider.maxRetryAttempts},
|
|
||||||
onSelectionChanged: (values) {
|
|
||||||
settingsProvider.setMaxRetryAttempts(values.first);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
Card(
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.all(16.0),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
const Icon(Icons.notifications_outlined),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Text(
|
|
||||||
'Notifications',
|
|
||||||
style: Theme.of(context).textTheme.titleMedium,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Text(
|
|
||||||
'View and manage pending notifications',
|
|
||||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
SizedBox(
|
|
||||||
width: double.infinity,
|
|
||||||
child: ElevatedButton.icon(
|
|
||||||
onPressed: () {
|
|
||||||
Navigator.of(context).push(
|
|
||||||
MaterialPageRoute(
|
|
||||||
builder: (context) => const PendingNotificationsScreen(),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
icon: const Icon(Icons.list),
|
|
||||||
label: const Text('View Pending Notifications'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
if (Theme.of(context).brightness == Brightness.dark) // Only show in debug mode for now
|
|
||||||
Card(
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.all(16.0),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Icon(Icons.bug_report, color: Colors.orange),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Text(
|
|
||||||
'Debug - Notifications',
|
|
||||||
style: Theme.of(context).textTheme.titleMedium,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
Consumer<SupplementProvider>(
|
|
||||||
builder: (context, supplementProvider, child) {
|
|
||||||
return Column(
|
|
||||||
children: [
|
|
||||||
ElevatedButton.icon(
|
|
||||||
onPressed: () async {
|
|
||||||
await supplementProvider.testNotifications();
|
|
||||||
if (context.mounted) {
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
const SnackBar(content: Text('Test notification sent!')),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
icon: const Icon(Icons.notifications_active),
|
|
||||||
label: const Text('Test Instant'),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
ElevatedButton.icon(
|
|
||||||
onPressed: () async {
|
|
||||||
await supplementProvider.testScheduledNotification();
|
|
||||||
if (context.mounted) {
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
const SnackBar(content: Text('Scheduled test notification for 1 minute from now!')),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
icon: const Icon(Icons.schedule),
|
|
||||||
label: const Text('Test Scheduled (1min)'),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
ElevatedButton.icon(
|
|
||||||
onPressed: () async {
|
|
||||||
await supplementProvider.testNotificationActions();
|
|
||||||
if (context.mounted) {
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
const SnackBar(content: Text('Test notification with actions sent! Try the Take/Snooze buttons.')),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
icon: const Icon(Icons.touch_app),
|
|
||||||
label: const Text('Test Actions'),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
ElevatedButton.icon(
|
|
||||||
onPressed: () async {
|
|
||||||
await NotificationService().testBasicNotification();
|
|
||||||
if (context.mounted) {
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
const SnackBar(content: Text('Basic test notification sent! Tap it to test callback.')),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
icon: const Icon(Icons.tap_and_play),
|
|
||||||
label: const Text('Test Basic Tap'),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
ElevatedButton.icon(
|
|
||||||
onPressed: () async {
|
|
||||||
await supplementProvider.rescheduleAllNotifications();
|
|
||||||
if (context.mounted) {
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
const SnackBar(content: Text('All notifications rescheduled!')),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
icon: const Icon(Icons.refresh),
|
|
||||||
label: const Text('Reschedule All'),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
ElevatedButton.icon(
|
|
||||||
onPressed: () async {
|
|
||||||
await supplementProvider.cancelAllNotifications();
|
|
||||||
if (context.mounted) {
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
const SnackBar(content: Text('All notifications cancelled!')),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
icon: const Icon(Icons.cancel),
|
|
||||||
label: const Text('Cancel All'),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
ElevatedButton.icon(
|
|
||||||
onPressed: () async {
|
|
||||||
final pending = await supplementProvider.getPendingNotifications();
|
|
||||||
if (context.mounted) {
|
|
||||||
showDialog(
|
|
||||||
context: context,
|
|
||||||
builder: (context) => AlertDialog(
|
|
||||||
title: const Text('Pending Notifications'),
|
|
||||||
content: pending.isEmpty
|
|
||||||
? const Text('No pending notifications')
|
|
||||||
: SizedBox(
|
|
||||||
width: double.maxFinite,
|
|
||||||
child: Consumer<SupplementProvider>(
|
|
||||||
builder: (context, provider, child) {
|
|
||||||
return ListView.builder(
|
|
||||||
shrinkWrap: true,
|
|
||||||
itemCount: pending.length,
|
|
||||||
itemBuilder: (context, index) {
|
|
||||||
final notification = pending[index];
|
|
||||||
|
|
||||||
// Calculate scheduled time inline
|
|
||||||
String scheduledTime = '';
|
|
||||||
try {
|
|
||||||
final notificationId = notification.id;
|
|
||||||
if (notificationId == 99999) {
|
|
||||||
scheduledTime = 'Test notification';
|
|
||||||
} else if (notificationId > 1000) {
|
|
||||||
final snoozeMinutes = notificationId % 1000;
|
|
||||||
scheduledTime = 'Snoozed ($snoozeMinutes min)';
|
|
||||||
} else {
|
|
||||||
final supplementId = notificationId ~/ 100;
|
|
||||||
final reminderIndex = notificationId % 100;
|
|
||||||
|
|
||||||
final supplement = provider.supplements.firstWhere(
|
|
||||||
(s) => s.id == supplementId,
|
|
||||||
orElse: () => provider.supplements.first,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (reminderIndex < supplement.reminderTimes.length) {
|
|
||||||
final reminderTime = supplement.reminderTimes[reminderIndex];
|
|
||||||
final now = DateTime.now();
|
|
||||||
final timeParts = reminderTime.split(':');
|
|
||||||
final hour = int.parse(timeParts[0]);
|
|
||||||
final minute = int.parse(timeParts[1]);
|
|
||||||
|
|
||||||
final today = DateTime(now.year, now.month, now.day, hour, minute);
|
|
||||||
final isToday = today.isAfter(now);
|
|
||||||
|
|
||||||
scheduledTime = '${isToday ? 'Today' : 'Tomorrow'} at $reminderTime';
|
|
||||||
} else {
|
|
||||||
scheduledTime = 'Unknown time';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
scheduledTime = 'ID: ${notification.id}';
|
|
||||||
}
|
|
||||||
|
|
||||||
return Card(
|
|
||||||
margin: const EdgeInsets.symmetric(vertical: 4),
|
|
||||||
child: ListTile(
|
|
||||||
leading: CircleAvatar(
|
|
||||||
backgroundColor: Theme.of(context).colorScheme.primary,
|
|
||||||
child: Text(
|
|
||||||
'${index + 1}',
|
|
||||||
style: TextStyle(
|
|
||||||
color: Theme.of(context).colorScheme.onPrimary,
|
|
||||||
fontWeight: FontWeight.bold,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
title: Text(
|
|
||||||
notification.title ?? 'No title',
|
|
||||||
style: const TextStyle(fontWeight: FontWeight.w600),
|
|
||||||
),
|
|
||||||
subtitle: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Text('ID: ${notification.id}'),
|
|
||||||
Text(notification.body ?? 'No body'),
|
|
||||||
if (scheduledTime.isNotEmpty) ...[
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
Container(
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Theme.of(context).colorScheme.primaryContainer,
|
|
||||||
borderRadius: BorderRadius.circular(12),
|
|
||||||
),
|
|
||||||
child: Text(
|
|
||||||
'⏰ $scheduledTime',
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 12,
|
|
||||||
fontWeight: FontWeight.w600,
|
|
||||||
color: Theme.of(context).colorScheme.onPrimaryContainer,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
|
||||||
isThreeLine: true,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
actions: [
|
|
||||||
TextButton(
|
|
||||||
onPressed: () => Navigator.of(context).pop(),
|
|
||||||
child: const Text('Close'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
icon: const Icon(Icons.list),
|
|
||||||
label: const Text('Show Pending'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
|||||||
849
lib/screens/simple_sync_settings_screen.dart
Normal file
849
lib/screens/simple_sync_settings_screen.dart
Normal file
@@ -0,0 +1,849 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:provider/provider.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});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<SimpleSyncSettingsScreen> createState() => _SimpleSyncSettingsScreenState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _SimpleSyncSettingsScreenState extends State<SimpleSyncSettingsScreen> {
|
||||||
|
final _formKey = GlobalKey<FormState>();
|
||||||
|
final _serverUrlController = TextEditingController();
|
||||||
|
final _usernameController = TextEditingController();
|
||||||
|
final _passwordController = TextEditingController();
|
||||||
|
final _remotePathController = TextEditingController();
|
||||||
|
|
||||||
|
String _previewUrl = '';
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_serverUrlController.addListener(_updatePreviewUrl);
|
||||||
|
_usernameController.addListener(_updatePreviewUrl);
|
||||||
|
_loadSavedConfiguration();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _loadSavedConfiguration() {
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
|
final syncProvider = context.read<SimpleSyncProvider>();
|
||||||
|
|
||||||
|
if (syncProvider.serverUrl != null) {
|
||||||
|
_serverUrlController.text = _extractHostnameFromUrl(syncProvider.serverUrl!);
|
||||||
|
}
|
||||||
|
if (syncProvider.username != null) {
|
||||||
|
_usernameController.text = syncProvider.username!;
|
||||||
|
}
|
||||||
|
if (syncProvider.password != null) {
|
||||||
|
_passwordController.text = syncProvider.password!;
|
||||||
|
}
|
||||||
|
if (syncProvider.remotePath != null) {
|
||||||
|
_remotePathController.text = syncProvider.remotePath!;
|
||||||
|
}
|
||||||
|
|
||||||
|
_updatePreviewUrl();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
String _extractHostnameFromUrl(String fullUrl) {
|
||||||
|
try {
|
||||||
|
final uri = Uri.parse(fullUrl);
|
||||||
|
return uri.host;
|
||||||
|
} catch (e) {
|
||||||
|
return fullUrl; // Return as-is if parsing fails
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _updatePreviewUrl() {
|
||||||
|
setState(() {
|
||||||
|
if (_serverUrlController.text.isNotEmpty && _usernameController.text.isNotEmpty) {
|
||||||
|
_previewUrl = _constructWebDAVUrl(_serverUrlController.text, _usernameController.text);
|
||||||
|
} else {
|
||||||
|
_previewUrl = '';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_serverUrlController.removeListener(_updatePreviewUrl);
|
||||||
|
_usernameController.removeListener(_updatePreviewUrl);
|
||||||
|
_serverUrlController.dispose();
|
||||||
|
_usernameController.dispose();
|
||||||
|
_passwordController.dispose();
|
||||||
|
_remotePathController.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
@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: 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(),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildStatusCard(SimpleSyncProvider syncProvider) {
|
||||||
|
IconData icon;
|
||||||
|
Color color;
|
||||||
|
String statusText = syncProvider.getStatusText();
|
||||||
|
|
||||||
|
switch (syncProvider.status) {
|
||||||
|
case SyncStatus.idle:
|
||||||
|
icon = syncProvider.isAutoSync ? Icons.sync_alt : Icons.sync;
|
||||||
|
color = Colors.blue;
|
||||||
|
break;
|
||||||
|
case SyncStatus.downloading:
|
||||||
|
case SyncStatus.merging:
|
||||||
|
case SyncStatus.uploading:
|
||||||
|
icon = syncProvider.isAutoSync ? Icons.sync_alt : Icons.sync;
|
||||||
|
color = syncProvider.isAutoSync ? Colors.deepOrange : Colors.orange;
|
||||||
|
break;
|
||||||
|
case SyncStatus.completed:
|
||||||
|
icon = syncProvider.isAutoSync ? Icons.check_circle_outline : Icons.check_circle;
|
||||||
|
color = Colors.green;
|
||||||
|
break;
|
||||||
|
case SyncStatus.error:
|
||||||
|
icon = Icons.error;
|
||||||
|
color = Colors.red;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Card(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(16.0),
|
||||||
|
child: Column(
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Icon(icon, color: color, size: 24),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
statusText,
|
||||||
|
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||||
|
color: color,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
// 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(
|
||||||
|
'Last sync: ${_formatDateTime(syncProvider.lastSyncTime!)}',
|
||||||
|
style: Theme.of(context).textTheme.bodySmall,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
// 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.withValues(alpha: 0.1),
|
||||||
|
borderRadius: BorderRadius.circular(4),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
_getErrorMessage(syncProvider),
|
||||||
|
style: const TextStyle(color: Colors.red),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.close, color: Colors.red),
|
||||||
|
onPressed: () => syncProvider.clearError(),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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: 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,
|
||||||
|
),
|
||||||
|
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.primaryContainer.withValues(alpha: 0.3),
|
||||||
|
borderRadius: BorderRadius.circular(8),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.info_outline,
|
||||||
|
size: 16,
|
||||||
|
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,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _testConnection() async {
|
||||||
|
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'
|
||||||
|
: _remotePathController.text.trim(),
|
||||||
|
);
|
||||||
|
|
||||||
|
final success = await syncProvider.testConnection();
|
||||||
|
|
||||||
|
if (mounted) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text(success
|
||||||
|
? 'Connection successful!'
|
||||||
|
: 'Connection failed. Check your settings.'),
|
||||||
|
backgroundColor: success ? Colors.green : Colors.red,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (mounted) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text('Connection test failed: $e'),
|
||||||
|
backgroundColor: Colors.red,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _configureSync() async {
|
||||||
|
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'
|
||||||
|
: _remotePathController.text.trim(),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (mounted) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
const SnackBar(
|
||||||
|
content: Text('Configuration saved successfully!'),
|
||||||
|
backgroundColor: Colors.green,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (mounted) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text('Failed to save configuration: $e'),
|
||||||
|
backgroundColor: Colors.red,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _syncDatabase() async {
|
||||||
|
final syncProvider = context.read<SimpleSyncProvider>();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await syncProvider.syncDatabase(isAutoSync: false);
|
||||||
|
|
||||||
|
if (mounted) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
const SnackBar(
|
||||||
|
content: Text('Manual sync completed!'),
|
||||||
|
backgroundColor: Colors.green,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (mounted) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text('Manual sync failed: $e'),
|
||||||
|
backgroundColor: Colors.red,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String _constructWebDAVUrl(String serverUrl, String username) {
|
||||||
|
// Remove any protocol prefix if present
|
||||||
|
String cleanUrl = serverUrl.trim();
|
||||||
|
if (cleanUrl.startsWith('http://')) {
|
||||||
|
cleanUrl = cleanUrl.substring(7);
|
||||||
|
} 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')}';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,9 +3,11 @@ import 'package:provider/provider.dart';
|
|||||||
|
|
||||||
import '../models/supplement.dart';
|
import '../models/supplement.dart';
|
||||||
import '../providers/settings_provider.dart';
|
import '../providers/settings_provider.dart';
|
||||||
|
import '../providers/simple_sync_provider.dart';
|
||||||
import '../providers/supplement_provider.dart';
|
import '../providers/supplement_provider.dart';
|
||||||
import '../providers/sync_provider.dart';
|
import '../services/database_sync_service.dart';
|
||||||
import '../widgets/supplement_card.dart';
|
import '../widgets/supplement_card.dart';
|
||||||
|
import '../widgets/dialogs/take_supplement_dialog.dart';
|
||||||
import 'add_supplement_screen.dart';
|
import 'add_supplement_screen.dart';
|
||||||
import 'archived_supplements_screen.dart';
|
import 'archived_supplements_screen.dart';
|
||||||
|
|
||||||
@@ -19,7 +21,7 @@ class SupplementsListScreen extends StatelessWidget {
|
|||||||
title: const Text('My Supplements'),
|
title: const Text('My Supplements'),
|
||||||
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
|
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
|
||||||
actions: [
|
actions: [
|
||||||
Consumer<SyncProvider>(
|
Consumer<SimpleSyncProvider>(
|
||||||
builder: (context, syncProvider, child) {
|
builder: (context, syncProvider, child) {
|
||||||
if (!syncProvider.isConfigured) {
|
if (!syncProvider.isConfigured) {
|
||||||
return const SizedBox.shrink();
|
return const SizedBox.shrink();
|
||||||
@@ -32,12 +34,13 @@ class SupplementsListScreen extends StatelessWidget {
|
|||||||
height: 20,
|
height: 20,
|
||||||
child: CircularProgressIndicator(strokeWidth: 2),
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
)
|
)
|
||||||
: syncProvider.status.name == 'success' &&
|
: syncProvider.status == SyncStatus.completed &&
|
||||||
DateTime.now().difference(syncProvider.lastSyncTime ?? DateTime.now()).inSeconds < 5
|
syncProvider.lastSyncTime != null &&
|
||||||
|
DateTime.now().difference(syncProvider.lastSyncTime!).inSeconds < 5
|
||||||
? const Icon(Icons.check, color: Colors.green)
|
? const Icon(Icons.check, color: Colors.green)
|
||||||
: const Icon(Icons.sync),
|
: const Icon(Icons.sync),
|
||||||
onPressed: syncProvider.isSyncing ? null : () {
|
onPressed: syncProvider.isSyncing ? null : () {
|
||||||
syncProvider.performManualSync();
|
syncProvider.syncDatabase();
|
||||||
},
|
},
|
||||||
tooltip: syncProvider.isSyncing ? 'Syncing...' : 'Force Sync',
|
tooltip: syncProvider.isSyncing ? 'Syncing...' : 'Force Sync',
|
||||||
);
|
);
|
||||||
@@ -56,8 +59,8 @@ class SupplementsListScreen extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
body: Consumer3<SupplementProvider, SettingsProvider, SyncProvider>(
|
body: Consumer2<SupplementProvider, SettingsProvider>(
|
||||||
builder: (context, provider, settingsProvider, syncProvider, child) {
|
builder: (context, provider, settingsProvider, child) {
|
||||||
if (provider.isLoading) {
|
if (provider.isLoading) {
|
||||||
return const Center(child: CircularProgressIndicator());
|
return const Center(child: CircularProgressIndicator());
|
||||||
}
|
}
|
||||||
@@ -105,6 +108,7 @@ class SupplementsListScreen extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Widget _buildGroupedSupplementsList(BuildContext context, List<Supplement> supplements, SettingsProvider settingsProvider) {
|
Widget _buildGroupedSupplementsList(BuildContext context, List<Supplement> supplements, SettingsProvider settingsProvider) {
|
||||||
|
final provider = Provider.of<SupplementProvider>(context, listen: false);
|
||||||
final groupedSupplements = _groupSupplementsByTimeOfDay(supplements, settingsProvider);
|
final groupedSupplements = _groupSupplementsByTimeOfDay(supplements, settingsProvider);
|
||||||
|
|
||||||
return ListView(
|
return ListView(
|
||||||
@@ -115,10 +119,11 @@ class SupplementsListScreen extends StatelessWidget {
|
|||||||
...groupedSupplements['morning']!.map((supplement) =>
|
...groupedSupplements['morning']!.map((supplement) =>
|
||||||
SupplementCard(
|
SupplementCard(
|
||||||
supplement: supplement,
|
supplement: supplement,
|
||||||
onTake: () => _showTakeDialog(context, supplement),
|
onTake: () => showTakeSupplementDialog(context, supplement),
|
||||||
onEdit: () => _editSupplement(context, supplement),
|
onEdit: () => _editSupplement(context, supplement),
|
||||||
onDelete: () => _deleteSupplement(context, supplement),
|
onDelete: () => _deleteSupplement(context, supplement),
|
||||||
onArchive: () => _archiveSupplement(context, supplement),
|
onArchive: () => _archiveSupplement(context, supplement),
|
||||||
|
onDuplicate: () => context.read<SupplementProvider>().duplicateSupplement(supplement.id!),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
@@ -129,10 +134,11 @@ class SupplementsListScreen extends StatelessWidget {
|
|||||||
...groupedSupplements['afternoon']!.map((supplement) =>
|
...groupedSupplements['afternoon']!.map((supplement) =>
|
||||||
SupplementCard(
|
SupplementCard(
|
||||||
supplement: supplement,
|
supplement: supplement,
|
||||||
onTake: () => _showTakeDialog(context, supplement),
|
onTake: () => showTakeSupplementDialog(context, supplement),
|
||||||
onEdit: () => _editSupplement(context, supplement),
|
onEdit: () => _editSupplement(context, supplement),
|
||||||
onDelete: () => _deleteSupplement(context, supplement),
|
onDelete: () => _deleteSupplement(context, supplement),
|
||||||
onArchive: () => _archiveSupplement(context, supplement),
|
onArchive: () => _archiveSupplement(context, supplement),
|
||||||
|
onDuplicate: () => context.read<SupplementProvider>().duplicateSupplement(supplement.id!),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
@@ -143,10 +149,11 @@ class SupplementsListScreen extends StatelessWidget {
|
|||||||
...groupedSupplements['evening']!.map((supplement) =>
|
...groupedSupplements['evening']!.map((supplement) =>
|
||||||
SupplementCard(
|
SupplementCard(
|
||||||
supplement: supplement,
|
supplement: supplement,
|
||||||
onTake: () => _showTakeDialog(context, supplement),
|
onTake: () => showTakeSupplementDialog(context, supplement),
|
||||||
onEdit: () => _editSupplement(context, supplement),
|
onEdit: () => _editSupplement(context, supplement),
|
||||||
onDelete: () => _deleteSupplement(context, supplement),
|
onDelete: () => _deleteSupplement(context, supplement),
|
||||||
onArchive: () => _archiveSupplement(context, supplement),
|
onArchive: () => _archiveSupplement(context, supplement),
|
||||||
|
onDuplicate: () => context.read<SupplementProvider>().duplicateSupplement(supplement.id!),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
@@ -157,10 +164,11 @@ class SupplementsListScreen extends StatelessWidget {
|
|||||||
...groupedSupplements['night']!.map((supplement) =>
|
...groupedSupplements['night']!.map((supplement) =>
|
||||||
SupplementCard(
|
SupplementCard(
|
||||||
supplement: supplement,
|
supplement: supplement,
|
||||||
onTake: () => _showTakeDialog(context, supplement),
|
onTake: () => showTakeSupplementDialog(context, supplement),
|
||||||
onEdit: () => _editSupplement(context, supplement),
|
onEdit: () => _editSupplement(context, supplement),
|
||||||
onDelete: () => _deleteSupplement(context, supplement),
|
onDelete: () => _deleteSupplement(context, supplement),
|
||||||
onArchive: () => _archiveSupplement(context, supplement),
|
onArchive: () => _archiveSupplement(context, supplement),
|
||||||
|
onDuplicate: () => context.read<SupplementProvider>().duplicateSupplement(supplement.id!),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
@@ -171,10 +179,11 @@ class SupplementsListScreen extends StatelessWidget {
|
|||||||
...groupedSupplements['anytime']!.map((supplement) =>
|
...groupedSupplements['anytime']!.map((supplement) =>
|
||||||
SupplementCard(
|
SupplementCard(
|
||||||
supplement: supplement,
|
supplement: supplement,
|
||||||
onTake: () => _showTakeDialog(context, supplement),
|
onTake: () => showTakeSupplementDialog(context, supplement),
|
||||||
onEdit: () => _editSupplement(context, supplement),
|
onEdit: () => _editSupplement(context, supplement),
|
||||||
onDelete: () => _deleteSupplement(context, supplement),
|
onDelete: () => _deleteSupplement(context, supplement),
|
||||||
onArchive: () => _archiveSupplement(context, supplement),
|
onArchive: () => _archiveSupplement(context, supplement),
|
||||||
|
onDuplicate: () => context.read<SupplementProvider>().duplicateSupplement(supplement.id!),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -1,782 +0,0 @@
|
|||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:provider/provider.dart';
|
|
||||||
|
|
||||||
import '../models/sync_enums.dart';
|
|
||||||
import '../providers/sync_provider.dart';
|
|
||||||
|
|
||||||
/// Screen for configuring WebDAV sync settings
|
|
||||||
class SyncSettingsScreen extends StatefulWidget {
|
|
||||||
const SyncSettingsScreen({super.key});
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<SyncSettingsScreen> createState() => _SyncSettingsScreenState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _SyncSettingsScreenState extends State<SyncSettingsScreen> {
|
|
||||||
final _formKey = GlobalKey<FormState>();
|
|
||||||
final _serverUrlController = TextEditingController();
|
|
||||||
final _usernameController = TextEditingController();
|
|
||||||
final _passwordController = TextEditingController();
|
|
||||||
final _deviceNameController = TextEditingController();
|
|
||||||
final _syncFolderController = TextEditingController();
|
|
||||||
|
|
||||||
bool _isPasswordVisible = false;
|
|
||||||
bool _isTestingConnection = false;
|
|
||||||
bool _isConfiguring = false;
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
_loadCurrentSettings();
|
|
||||||
}
|
|
||||||
|
|
||||||
void _loadCurrentSettings() {
|
|
||||||
final syncProvider = context.read<SyncProvider>();
|
|
||||||
_serverUrlController.text = syncProvider.serverUrl ?? '';
|
|
||||||
_usernameController.text = syncProvider.username ?? '';
|
|
||||||
_syncFolderController.text = syncProvider.syncFolderName ?? 'Supplements';
|
|
||||||
// Note: We don't load the password for security reasons
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void dispose() {
|
|
||||||
_serverUrlController.dispose();
|
|
||||||
_usernameController.dispose();
|
|
||||||
_passwordController.dispose();
|
|
||||||
_deviceNameController.dispose();
|
|
||||||
_syncFolderController.dispose();
|
|
||||||
super.dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return Scaffold(
|
|
||||||
appBar: AppBar(
|
|
||||||
title: const Text('Cloud Sync Settings'),
|
|
||||||
actions: [
|
|
||||||
Consumer<SyncProvider>(
|
|
||||||
builder: (context, syncProvider, child) {
|
|
||||||
if (!syncProvider.isConfigured) return const SizedBox.shrink();
|
|
||||||
|
|
||||||
return PopupMenuButton<String>(
|
|
||||||
onSelected: (value) {
|
|
||||||
switch (value) {
|
|
||||||
case 'test':
|
|
||||||
_testConnection();
|
|
||||||
break;
|
|
||||||
case 'sync':
|
|
||||||
_performSync();
|
|
||||||
break;
|
|
||||||
case 'clear':
|
|
||||||
_showClearConfigDialog();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
itemBuilder: (context) => [
|
|
||||||
const PopupMenuItem(
|
|
||||||
value: 'test',
|
|
||||||
child: ListTile(
|
|
||||||
leading: Icon(Icons.wifi_protected_setup),
|
|
||||||
title: Text('Test Connection'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const PopupMenuItem(
|
|
||||||
value: 'sync',
|
|
||||||
child: ListTile(
|
|
||||||
leading: Icon(Icons.sync),
|
|
||||||
title: Text('Sync Now'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const PopupMenuItem(
|
|
||||||
value: 'clear',
|
|
||||||
child: ListTile(
|
|
||||||
leading: Icon(Icons.clear),
|
|
||||||
title: Text('Clear Configuration'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
body: Consumer<SyncProvider>(
|
|
||||||
builder: (context, syncProvider, child) {
|
|
||||||
return SingleChildScrollView(
|
|
||||||
padding: const EdgeInsets.all(16),
|
|
||||||
child: Form(
|
|
||||||
key: _formKey,
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
_buildStatusCard(syncProvider),
|
|
||||||
const SizedBox(height: 24),
|
|
||||||
_buildDeviceInfoSection(syncProvider),
|
|
||||||
const SizedBox(height: 24),
|
|
||||||
_buildConfigurationSection(syncProvider),
|
|
||||||
const SizedBox(height: 24),
|
|
||||||
_buildSyncSettingsSection(syncProvider),
|
|
||||||
if (syncProvider.hasPendingConflicts) ...[
|
|
||||||
const SizedBox(height: 24),
|
|
||||||
_buildConflictsSection(syncProvider),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildStatusCard(SyncProvider syncProvider) {
|
|
||||||
Color statusColor;
|
|
||||||
IconData statusIcon;
|
|
||||||
|
|
||||||
switch (syncProvider.status) {
|
|
||||||
case SyncOperationStatus.success:
|
|
||||||
statusColor = Colors.green;
|
|
||||||
statusIcon = Icons.check_circle;
|
|
||||||
break;
|
|
||||||
case SyncOperationStatus.syncing:
|
|
||||||
statusColor = Colors.blue;
|
|
||||||
statusIcon = Icons.sync;
|
|
||||||
break;
|
|
||||||
case SyncOperationStatus.networkError:
|
|
||||||
case SyncOperationStatus.authenticationError:
|
|
||||||
case SyncOperationStatus.serverError:
|
|
||||||
statusColor = Colors.red;
|
|
||||||
statusIcon = Icons.error;
|
|
||||||
break;
|
|
||||||
case SyncOperationStatus.conflictsDetected:
|
|
||||||
statusColor = Colors.orange;
|
|
||||||
statusIcon = Icons.warning;
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
statusColor = Colors.grey;
|
|
||||||
statusIcon = Icons.cloud_off;
|
|
||||||
}
|
|
||||||
|
|
||||||
return Card(
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.all(16),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Icon(statusIcon, color: statusColor, size: 24),
|
|
||||||
const SizedBox(width: 12),
|
|
||||||
Expanded(
|
|
||||||
child: Text(
|
|
||||||
syncProvider.statusMessage,
|
|
||||||
style: Theme.of(context).textTheme.titleMedium,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
if (syncProvider.lastSyncTime != null) ...[
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Text(
|
|
||||||
'Last sync: ${syncProvider.formattedLastSyncTime}',
|
|
||||||
style: Theme.of(context).textTheme.bodySmall,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
if (syncProvider.isConfigured && syncProvider.detectedServerType != null) ...[
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Icon(Icons.check_circle, size: 16, color: Colors.green),
|
|
||||||
const SizedBox(width: 4),
|
|
||||||
Text(
|
|
||||||
'Detected: ${syncProvider.detectedServerType}',
|
|
||||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
|
||||||
color: Colors.green[700],
|
|
||||||
fontWeight: FontWeight.w500,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
],
|
|
||||||
if (syncProvider.hasError) ...[
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Text(
|
|
||||||
syncProvider.currentError!,
|
|
||||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
|
||||||
color: Colors.red,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
if (syncProvider.isSyncing) ...[
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
LinearProgressIndicator(
|
|
||||||
value: syncProvider.syncProgress,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildConfigurationSection(SyncProvider syncProvider) {
|
|
||||||
return Card(
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.all(16),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Text(
|
|
||||||
'WebDAV Configuration',
|
|
||||||
style: Theme.of(context).textTheme.titleMedium,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
TextFormField(
|
|
||||||
controller: _serverUrlController,
|
|
||||||
decoration: const InputDecoration(
|
|
||||||
labelText: 'Server URL',
|
|
||||||
hintText: 'cloud.example.com or drive.mydomain.com',
|
|
||||||
prefixIcon: Icon(Icons.cloud),
|
|
||||||
helperText: 'Just enter your server domain - we\'ll auto-detect the rest!',
|
|
||||||
helperMaxLines: 2,
|
|
||||||
),
|
|
||||||
validator: (value) {
|
|
||||||
if (value?.isEmpty ?? true) {
|
|
||||||
return 'Please enter server URL';
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
},
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Container(
|
|
||||||
padding: const EdgeInsets.all(12),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Colors.blue.withOpacity(0.1),
|
|
||||||
borderRadius: BorderRadius.circular(8),
|
|
||||||
border: Border.all(color: Colors.blue.withOpacity(0.3)),
|
|
||||||
),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Icon(Icons.lightbulb_outline, size: 16, color: Colors.blue[700]),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Text(
|
|
||||||
'Smart URL Detection',
|
|
||||||
style: Theme.of(context).textTheme.titleSmall?.copyWith(
|
|
||||||
color: Colors.blue[700],
|
|
||||||
fontWeight: FontWeight.bold,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Text(
|
|
||||||
'You can enter simple URLs like:',
|
|
||||||
style: Theme.of(context).textTheme.bodySmall,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
Text(
|
|
||||||
'• cloud.example.com\n'
|
|
||||||
'• drive.mydomain.com\n'
|
|
||||||
'• nextcloud.company.org\n'
|
|
||||||
'• my-server.duckdns.org:8080',
|
|
||||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
|
||||||
fontFamily: 'monospace',
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Text(
|
|
||||||
'We\'ll automatically detect if it\'s Nextcloud, ownCloud, or generic WebDAV and build the correct URL for you!',
|
|
||||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
|
||||||
fontStyle: FontStyle.italic,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
TextFormField(
|
|
||||||
controller: _usernameController,
|
|
||||||
decoration: const InputDecoration(
|
|
||||||
labelText: 'Username',
|
|
||||||
prefixIcon: Icon(Icons.person),
|
|
||||||
),
|
|
||||||
validator: (value) {
|
|
||||||
if (value?.isEmpty ?? true) {
|
|
||||||
return 'Please enter username';
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
},
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
TextFormField(
|
|
||||||
controller: _passwordController,
|
|
||||||
obscureText: !_isPasswordVisible,
|
|
||||||
decoration: InputDecoration(
|
|
||||||
labelText: 'Password / App Password',
|
|
||||||
prefixIcon: const Icon(Icons.lock),
|
|
||||||
suffixIcon: IconButton(
|
|
||||||
icon: Icon(
|
|
||||||
_isPasswordVisible ? Icons.visibility : Icons.visibility_off,
|
|
||||||
),
|
|
||||||
onPressed: () {
|
|
||||||
setState(() {
|
|
||||||
_isPasswordVisible = !_isPasswordVisible;
|
|
||||||
});
|
|
||||||
},
|
|
||||||
),
|
|
||||||
helperText: 'Use app passwords for better security',
|
|
||||||
),
|
|
||||||
validator: (value) {
|
|
||||||
if (value?.isEmpty ?? true) {
|
|
||||||
return 'Please enter password';
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
},
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
TextFormField(
|
|
||||||
controller: _syncFolderController,
|
|
||||||
decoration: const InputDecoration(
|
|
||||||
labelText: 'Sync Folder Name',
|
|
||||||
prefixIcon: Icon(Icons.folder),
|
|
||||||
hintText: 'Supplements',
|
|
||||||
helperText: 'Folder name on your cloud server for syncing data',
|
|
||||||
),
|
|
||||||
validator: (value) {
|
|
||||||
if (value?.isEmpty ?? true) {
|
|
||||||
return 'Please enter folder name';
|
|
||||||
}
|
|
||||||
if (value!.contains('/') || value.contains('\\')) {
|
|
||||||
return 'Folder name cannot contain slashes';
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
},
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
TextFormField(
|
|
||||||
controller: _deviceNameController,
|
|
||||||
decoration: const InputDecoration(
|
|
||||||
labelText: 'Device Name (Optional)',
|
|
||||||
prefixIcon: Icon(Icons.phone_android),
|
|
||||||
hintText: 'My Phone',
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 24),
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: ElevatedButton.icon(
|
|
||||||
onPressed: _isConfiguring || syncProvider.isSyncing
|
|
||||||
? null
|
|
||||||
: () => _configureWebDAV(syncProvider),
|
|
||||||
icon: _isConfiguring
|
|
||||||
? const SizedBox(
|
|
||||||
width: 16,
|
|
||||||
height: 16,
|
|
||||||
child: CircularProgressIndicator(strokeWidth: 2),
|
|
||||||
)
|
|
||||||
: const Icon(Icons.save),
|
|
||||||
label: Text(syncProvider.isConfigured ? 'Update' : 'Configure'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
if (syncProvider.isConfigured) ...[
|
|
||||||
const SizedBox(width: 12),
|
|
||||||
ElevatedButton.icon(
|
|
||||||
onPressed: _isTestingConnection || syncProvider.isSyncing
|
|
||||||
? null
|
|
||||||
: _testConnection,
|
|
||||||
icon: _isTestingConnection
|
|
||||||
? const SizedBox(
|
|
||||||
width: 16,
|
|
||||||
height: 16,
|
|
||||||
child: CircularProgressIndicator(strokeWidth: 2),
|
|
||||||
)
|
|
||||||
: const Icon(Icons.wifi_protected_setup),
|
|
||||||
label: const Text('Test'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildSyncSettingsSection(SyncProvider syncProvider) {
|
|
||||||
if (!syncProvider.isConfigured) return const SizedBox.shrink();
|
|
||||||
|
|
||||||
return Card(
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.all(16),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Text(
|
|
||||||
'Sync Settings',
|
|
||||||
style: Theme.of(context).textTheme.titleMedium,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
SwitchListTile(
|
|
||||||
title: const Text('Auto Sync on Data Changes'),
|
|
||||||
subtitle: const Text('Automatically sync when you add, modify, or take supplements'),
|
|
||||||
value: syncProvider.autoSyncOnDataChanges,
|
|
||||||
onChanged: syncProvider.setAutoSyncOnDataChanges,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
ListTile(
|
|
||||||
title: const Text('Conflict Resolution'),
|
|
||||||
subtitle: Text(_getConflictStrategyDescription(syncProvider.conflictStrategy)),
|
|
||||||
trailing: DropdownButton<ConflictResolutionStrategy>(
|
|
||||||
value: syncProvider.conflictStrategy,
|
|
||||||
onChanged: (strategy) {
|
|
||||||
if (strategy != null) {
|
|
||||||
syncProvider.setConflictResolutionStrategy(strategy);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
items: ConflictResolutionStrategy.values
|
|
||||||
.map((strategy) => DropdownMenuItem(
|
|
||||||
value: strategy,
|
|
||||||
child: Text(_getConflictStrategyName(strategy)),
|
|
||||||
))
|
|
||||||
.toList(),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
SizedBox(
|
|
||||||
width: double.infinity,
|
|
||||||
child: ElevatedButton.icon(
|
|
||||||
onPressed: syncProvider.isSyncing ? null : _performSync,
|
|
||||||
icon: syncProvider.isSyncing
|
|
||||||
? const SizedBox(
|
|
||||||
width: 16,
|
|
||||||
height: 16,
|
|
||||||
child: CircularProgressIndicator(strokeWidth: 2),
|
|
||||||
)
|
|
||||||
: const Icon(Icons.sync),
|
|
||||||
label: const Text('Sync Now'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildConflictsSection(SyncProvider syncProvider) {
|
|
||||||
return Card(
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.all(16),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
const Icon(Icons.warning, color: Colors.orange),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Text(
|
|
||||||
'Sync Conflicts',
|
|
||||||
style: Theme.of(context).textTheme.titleMedium,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
Text(
|
|
||||||
'${syncProvider.pendingConflicts.length} conflicts need your attention',
|
|
||||||
style: Theme.of(context).textTheme.bodyMedium,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: ElevatedButton(
|
|
||||||
onPressed: () => _showConflictsDialog(syncProvider),
|
|
||||||
child: const Text('Review Conflicts'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 12),
|
|
||||||
ElevatedButton(
|
|
||||||
onPressed: syncProvider.resolveAllConflicts,
|
|
||||||
child: const Text('Auto Resolve'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildDeviceInfoSection(SyncProvider syncProvider) {
|
|
||||||
return Card(
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.all(16),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Text(
|
|
||||||
'Connection Information',
|
|
||||||
style: Theme.of(context).textTheme.titleMedium,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
FutureBuilder<Map<String, String?>>(
|
|
||||||
future: syncProvider.getDeviceInfo(),
|
|
||||||
builder: (context, snapshot) {
|
|
||||||
if (!snapshot.hasData) {
|
|
||||||
return const Center(child: CircularProgressIndicator());
|
|
||||||
}
|
|
||||||
|
|
||||||
final deviceInfo = snapshot.data!;
|
|
||||||
return Column(
|
|
||||||
children: [
|
|
||||||
if (syncProvider.detectedServerType != null)
|
|
||||||
ListTile(
|
|
||||||
leading: const Icon(Icons.cloud_done),
|
|
||||||
title: const Text('Server Type'),
|
|
||||||
subtitle: Text(syncProvider.detectedServerType!),
|
|
||||||
),
|
|
||||||
if (syncProvider.finalWebdavUrl != null)
|
|
||||||
ListTile(
|
|
||||||
leading: const Icon(Icons.link),
|
|
||||||
title: const Text('WebDAV URL'),
|
|
||||||
subtitle: Text(
|
|
||||||
syncProvider.finalWebdavUrl!,
|
|
||||||
style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
ListTile(
|
|
||||||
leading: const Icon(Icons.fingerprint),
|
|
||||||
title: const Text('Device ID'),
|
|
||||||
subtitle: Text(deviceInfo['deviceId'] ?? 'Unknown'),
|
|
||||||
),
|
|
||||||
ListTile(
|
|
||||||
leading: const Icon(Icons.devices),
|
|
||||||
title: const Text('Device Name'),
|
|
||||||
subtitle: Text(deviceInfo['deviceName'] ?? 'Unknown'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
String _getConflictStrategyName(ConflictResolutionStrategy strategy) {
|
|
||||||
switch (strategy) {
|
|
||||||
case ConflictResolutionStrategy.preferLocal:
|
|
||||||
return 'Prefer Local';
|
|
||||||
case ConflictResolutionStrategy.preferRemote:
|
|
||||||
return 'Prefer Remote';
|
|
||||||
case ConflictResolutionStrategy.preferNewer:
|
|
||||||
return 'Prefer Newer';
|
|
||||||
case ConflictResolutionStrategy.manual:
|
|
||||||
return 'Manual';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String _getConflictStrategyDescription(ConflictResolutionStrategy strategy) {
|
|
||||||
switch (strategy) {
|
|
||||||
case ConflictResolutionStrategy.preferLocal:
|
|
||||||
return 'Always keep local changes';
|
|
||||||
case ConflictResolutionStrategy.preferRemote:
|
|
||||||
return 'Always keep remote changes';
|
|
||||||
case ConflictResolutionStrategy.preferNewer:
|
|
||||||
return 'Keep most recent changes';
|
|
||||||
case ConflictResolutionStrategy.manual:
|
|
||||||
return 'Review each conflict manually';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _configureWebDAV(SyncProvider syncProvider) async {
|
|
||||||
// For updates, allow empty password to keep existing one
|
|
||||||
if (syncProvider.isConfigured && _passwordController.text.isEmpty) {
|
|
||||||
// Skip validation for password on updates
|
|
||||||
if (_serverUrlController.text.trim().isEmpty || _usernameController.text.trim().isEmpty) {
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
const SnackBar(
|
|
||||||
content: Text('Please fill in server URL and username'),
|
|
||||||
backgroundColor: Colors.red,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
} else if (!_formKey.currentState!.validate()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setState(() => _isConfiguring = true);
|
|
||||||
|
|
||||||
final success = await syncProvider.configure(
|
|
||||||
serverUrl: _serverUrlController.text.trim(),
|
|
||||||
username: _usernameController.text.trim(),
|
|
||||||
password: _passwordController.text.isEmpty ? null : _passwordController.text,
|
|
||||||
deviceName: _deviceNameController.text.trim().isEmpty
|
|
||||||
? null
|
|
||||||
: _deviceNameController.text.trim(),
|
|
||||||
syncFolderName: _syncFolderController.text.trim().isEmpty
|
|
||||||
? 'Supplements'
|
|
||||||
: _syncFolderController.text.trim(),
|
|
||||||
);
|
|
||||||
|
|
||||||
setState(() => _isConfiguring = false);
|
|
||||||
|
|
||||||
if (mounted) {
|
|
||||||
final message = success
|
|
||||||
? 'WebDAV configured successfully!'
|
|
||||||
: 'Failed to configure WebDAV';
|
|
||||||
|
|
||||||
final detectionInfo = success && syncProvider.detectedServerType != null
|
|
||||||
? '\nDetected: ${syncProvider.detectedServerType}'
|
|
||||||
: '';
|
|
||||||
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
SnackBar(
|
|
||||||
content: Text('$message$detectionInfo'),
|
|
||||||
backgroundColor: success ? Colors.green : Colors.red,
|
|
||||||
duration: Duration(seconds: success ? 4 : 3),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
if (success) {
|
|
||||||
_passwordController.clear(); // Clear password for security
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _testConnection() async {
|
|
||||||
setState(() => _isTestingConnection = true);
|
|
||||||
|
|
||||||
final syncProvider = context.read<SyncProvider>();
|
|
||||||
final success = await syncProvider.testConnection();
|
|
||||||
|
|
||||||
setState(() => _isTestingConnection = false);
|
|
||||||
|
|
||||||
if (mounted) {
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
SnackBar(
|
|
||||||
content: Text(success
|
|
||||||
? 'Connection test successful!'
|
|
||||||
: 'Connection test failed'),
|
|
||||||
backgroundColor: success ? Colors.green : Colors.red,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _performSync() async {
|
|
||||||
final syncProvider = context.read<SyncProvider>();
|
|
||||||
final success = await syncProvider.performManualSync();
|
|
||||||
|
|
||||||
if (mounted) {
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
SnackBar(
|
|
||||||
content: Text(success
|
|
||||||
? 'Sync completed successfully!'
|
|
||||||
: 'Sync failed'),
|
|
||||||
backgroundColor: success ? Colors.green : Colors.red,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _showClearConfigDialog() async {
|
|
||||||
final confirmed = await showDialog<bool>(
|
|
||||||
context: context,
|
|
||||||
builder: (context) => AlertDialog(
|
|
||||||
title: const Text('Clear Configuration'),
|
|
||||||
content: const Text(
|
|
||||||
'Are you sure you want to clear the WebDAV configuration? '
|
|
||||||
'This will disable cloud sync.',
|
|
||||||
),
|
|
||||||
actions: [
|
|
||||||
TextButton(
|
|
||||||
onPressed: () => Navigator.of(context).pop(false),
|
|
||||||
child: const Text('Cancel'),
|
|
||||||
),
|
|
||||||
TextButton(
|
|
||||||
onPressed: () => Navigator.of(context).pop(true),
|
|
||||||
child: const Text('Clear'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
if (confirmed == true) {
|
|
||||||
final syncProvider = context.read<SyncProvider>();
|
|
||||||
await syncProvider.clearConfiguration();
|
|
||||||
_serverUrlController.clear();
|
|
||||||
_usernameController.clear();
|
|
||||||
_passwordController.clear();
|
|
||||||
_deviceNameController.clear();
|
|
||||||
|
|
||||||
if (mounted) {
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
const SnackBar(
|
|
||||||
content: Text('Configuration cleared'),
|
|
||||||
backgroundColor: Colors.orange,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _showConflictsDialog(SyncProvider syncProvider) async {
|
|
||||||
await showDialog(
|
|
||||||
context: context,
|
|
||||||
builder: (context) => AlertDialog(
|
|
||||||
title: const Text('Sync Conflicts'),
|
|
||||||
content: SizedBox(
|
|
||||||
width: double.maxFinite,
|
|
||||||
height: 300,
|
|
||||||
child: ListView.builder(
|
|
||||||
itemCount: syncProvider.pendingConflicts.length,
|
|
||||||
itemBuilder: (context, index) {
|
|
||||||
final conflict = syncProvider.pendingConflicts[index];
|
|
||||||
return Card(
|
|
||||||
child: ListTile(
|
|
||||||
title: Text(conflict.type.name),
|
|
||||||
subtitle: Text(conflict.description),
|
|
||||||
trailing: Row(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
TextButton(
|
|
||||||
onPressed: () {
|
|
||||||
syncProvider.resolveConflict(
|
|
||||||
conflict.syncId,
|
|
||||||
ConflictResolution.useLocal,
|
|
||||||
);
|
|
||||||
},
|
|
||||||
child: const Text('Local'),
|
|
||||||
),
|
|
||||||
TextButton(
|
|
||||||
onPressed: () {
|
|
||||||
syncProvider.resolveConflict(
|
|
||||||
conflict.syncId,
|
|
||||||
ConflictResolution.useRemote,
|
|
||||||
);
|
|
||||||
},
|
|
||||||
child: const Text('Remote'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
actions: [
|
|
||||||
TextButton(
|
|
||||||
onPressed: () => Navigator.of(context).pop(),
|
|
||||||
child: const Text('Close'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
471
lib/services/auto_sync_service.dart
Normal file
471
lib/services/auto_sync_service.dart
Normal file
@@ -0,0 +1,471 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:io';
|
||||||
|
import 'dart:math';
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:supplements/logging.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) {
|
||||||
|
printLog('AutoSyncService: Auto-sync is disabled, skipping trigger');
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if auto-sync was disabled due to persistent errors
|
||||||
|
if (_autoDisabledDueToErrors) {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('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) {
|
||||||
|
printLog('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) {
|
||||||
|
printLog('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) {
|
||||||
|
printLog('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) {
|
||||||
|
printLog('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) {
|
||||||
|
printLog('AutoSyncService: Auto-sync disabled during execution, aborting');
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_autoDisabledDueToErrors) {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('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) {
|
||||||
|
printLog('AutoSyncService: Sync not configured during execution, aborting');
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_syncInProgress || _syncProvider.isSyncing) {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('AutoSyncService: Sync already in progress during execution, aborting');
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_syncInProgress = true;
|
||||||
|
_hasPendingSync = false;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('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) {
|
||||||
|
printLog('AutoSyncService: Auto-sync completed successfully');
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('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) {
|
||||||
|
printLog('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) {
|
||||||
|
printLog('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) {
|
||||||
|
printLog('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) {
|
||||||
|
printLog('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) {
|
||||||
|
printLog('AutoSyncService: Retrying auto-sync after backoff delay');
|
||||||
|
}
|
||||||
|
triggerAutoSync();
|
||||||
|
});
|
||||||
|
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('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) {
|
||||||
|
printLog('AutoSyncService: Network check failed: $e');
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cancels any pending sync operation
|
||||||
|
void cancelPendingSync() {
|
||||||
|
_cancelPendingSync();
|
||||||
|
_retryTimer?.cancel();
|
||||||
|
_retryTimer = null;
|
||||||
|
_hasPendingSync = false;
|
||||||
|
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('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) {
|
||||||
|
printLog('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) {
|
||||||
|
printLog('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;
|
||||||
|
}
|
||||||
@@ -6,7 +6,7 @@ import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
|||||||
|
|
||||||
import '../models/supplement.dart';
|
import '../models/supplement.dart';
|
||||||
import '../models/supplement_intake.dart';
|
import '../models/supplement_intake.dart';
|
||||||
import '../models/sync_enums.dart';
|
import 'database_sync_service.dart';
|
||||||
|
|
||||||
class DatabaseHelper {
|
class DatabaseHelper {
|
||||||
static const _databaseName = 'supplements.db';
|
static const _databaseName = 'supplements.db';
|
||||||
@@ -399,7 +399,43 @@ class DatabaseHelper {
|
|||||||
Database db = await database;
|
Database db = await database;
|
||||||
return await db.update(
|
return await db.update(
|
||||||
supplementsTable,
|
supplementsTable,
|
||||||
{'isActive': 0},
|
{
|
||||||
|
'isActive': 0,
|
||||||
|
'isDeleted': 1,
|
||||||
|
'lastModified': DateTime.now().toIso8601String(),
|
||||||
|
},
|
||||||
|
where: 'id = ?',
|
||||||
|
whereArgs: [id],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<int> permanentlyDeleteSupplement(int id) async {
|
||||||
|
Database db = await database;
|
||||||
|
|
||||||
|
// For sync compatibility, we should mark as deleted rather than completely removing
|
||||||
|
// This prevents the supplement from reappearing during sync
|
||||||
|
|
||||||
|
// First mark all related intakes as deleted
|
||||||
|
await db.update(
|
||||||
|
intakesTable,
|
||||||
|
{
|
||||||
|
'isDeleted': 1,
|
||||||
|
'lastModified': DateTime.now().toIso8601String(),
|
||||||
|
'syncStatus': RecordSyncStatus.modified.name,
|
||||||
|
},
|
||||||
|
where: 'supplementId = ? AND isDeleted = ?',
|
||||||
|
whereArgs: [id, 0],
|
||||||
|
);
|
||||||
|
|
||||||
|
// Then mark the supplement as deleted instead of removing it completely
|
||||||
|
return await db.update(
|
||||||
|
supplementsTable,
|
||||||
|
{
|
||||||
|
'isDeleted': 1,
|
||||||
|
'isActive': 0, // Also ensure it's archived
|
||||||
|
'lastModified': DateTime.now().toIso8601String(),
|
||||||
|
'syncStatus': RecordSyncStatus.modified.name,
|
||||||
|
},
|
||||||
where: 'id = ?',
|
where: 'id = ?',
|
||||||
whereArgs: [id],
|
whereArgs: [id],
|
||||||
);
|
);
|
||||||
@@ -411,6 +447,36 @@ class DatabaseHelper {
|
|||||||
return await db.insert(intakesTable, intake.toMap());
|
return await db.insert(intakesTable, intake.toMap());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<int> deleteIntake(int id) async {
|
||||||
|
Database db = await database;
|
||||||
|
return await db.update(
|
||||||
|
intakesTable,
|
||||||
|
{
|
||||||
|
'isDeleted': 1,
|
||||||
|
'lastModified': DateTime.now().toIso8601String(),
|
||||||
|
},
|
||||||
|
where: 'id = ?',
|
||||||
|
whereArgs: [id],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<int> permanentlyDeleteIntake(int id) async {
|
||||||
|
Database db = await database;
|
||||||
|
|
||||||
|
// For sync compatibility, mark as deleted rather than completely removing
|
||||||
|
// This prevents the intake from reappearing during sync
|
||||||
|
return await db.update(
|
||||||
|
intakesTable,
|
||||||
|
{
|
||||||
|
'isDeleted': 1,
|
||||||
|
'lastModified': DateTime.now().toIso8601String(),
|
||||||
|
'syncStatus': RecordSyncStatus.modified.name,
|
||||||
|
},
|
||||||
|
where: 'id = ?',
|
||||||
|
whereArgs: [id],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
Future<List<SupplementIntake>> getIntakesForDate(DateTime date) async {
|
Future<List<SupplementIntake>> getIntakesForDate(DateTime date) async {
|
||||||
Database db = await database;
|
Database db = await database;
|
||||||
String startDate = DateTime(date.year, date.month, date.day).toIso8601String();
|
String startDate = DateTime(date.year, date.month, date.day).toIso8601String();
|
||||||
@@ -477,15 +543,6 @@ class DatabaseHelper {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<int> deleteIntake(int id) async {
|
|
||||||
Database db = await database;
|
|
||||||
return await db.delete(
|
|
||||||
intakesTable,
|
|
||||||
where: 'id = ?',
|
|
||||||
whereArgs: [id],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Notification tracking methods
|
// Notification tracking methods
|
||||||
Future<int> trackNotification({
|
Future<int> trackNotification({
|
||||||
required int notificationId,
|
required int notificationId,
|
||||||
@@ -637,7 +694,7 @@ class DatabaseHelper {
|
|||||||
List<Map<String, dynamic>> maps = await db.query(
|
List<Map<String, dynamic>> maps = await db.query(
|
||||||
supplementsTable,
|
supplementsTable,
|
||||||
where: 'syncStatus IN (?, ?)',
|
where: 'syncStatus IN (?, ?)',
|
||||||
whereArgs: [SyncStatus.pending.name, SyncStatus.modified.name],
|
whereArgs: [RecordSyncStatus.pending.name, RecordSyncStatus.modified.name],
|
||||||
orderBy: 'lastModified ASC',
|
orderBy: 'lastModified ASC',
|
||||||
);
|
);
|
||||||
return List.generate(maps.length, (i) => Supplement.fromMap(maps[i]));
|
return List.generate(maps.length, (i) => Supplement.fromMap(maps[i]));
|
||||||
@@ -648,7 +705,7 @@ class DatabaseHelper {
|
|||||||
List<Map<String, dynamic>> maps = await db.query(
|
List<Map<String, dynamic>> maps = await db.query(
|
||||||
intakesTable,
|
intakesTable,
|
||||||
where: 'syncStatus IN (?, ?)',
|
where: 'syncStatus IN (?, ?)',
|
||||||
whereArgs: [SyncStatus.pending.name, SyncStatus.modified.name],
|
whereArgs: [RecordSyncStatus.pending.name, RecordSyncStatus.modified.name],
|
||||||
orderBy: 'lastModified ASC',
|
orderBy: 'lastModified ASC',
|
||||||
);
|
);
|
||||||
return List.generate(maps.length, (i) => SupplementIntake.fromMap(maps[i]));
|
return List.generate(maps.length, (i) => SupplementIntake.fromMap(maps[i]));
|
||||||
@@ -658,7 +715,7 @@ class DatabaseHelper {
|
|||||||
Database db = await database;
|
Database db = await database;
|
||||||
await db.update(
|
await db.update(
|
||||||
supplementsTable,
|
supplementsTable,
|
||||||
{'syncStatus': SyncStatus.synced.name},
|
{'syncStatus': RecordSyncStatus.synced.name},
|
||||||
where: 'syncId = ?',
|
where: 'syncId = ?',
|
||||||
whereArgs: [syncId],
|
whereArgs: [syncId],
|
||||||
);
|
);
|
||||||
@@ -668,7 +725,7 @@ class DatabaseHelper {
|
|||||||
Database db = await database;
|
Database db = await database;
|
||||||
await db.update(
|
await db.update(
|
||||||
intakesTable,
|
intakesTable,
|
||||||
{'syncStatus': SyncStatus.synced.name},
|
{'syncStatus': RecordSyncStatus.synced.name},
|
||||||
where: 'syncId = ?',
|
where: 'syncId = ?',
|
||||||
whereArgs: [syncId],
|
whereArgs: [syncId],
|
||||||
);
|
);
|
||||||
|
|||||||
533
lib/services/database_sync_service.dart
Normal file
533
lib/services/database_sync_service.dart
Normal file
@@ -0,0 +1,533 @@
|
|||||||
|
import 'dart:io' as io;
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:path/path.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:sqflite/sqflite.dart';
|
||||||
|
import 'package:supplements/logging.dart';
|
||||||
|
import 'package:webdav_client/webdav_client.dart';
|
||||||
|
|
||||||
|
import '../models/supplement.dart';
|
||||||
|
import '../models/supplement_intake.dart';
|
||||||
|
import 'database_helper.dart';
|
||||||
|
|
||||||
|
enum SyncStatus {
|
||||||
|
idle,
|
||||||
|
downloading,
|
||||||
|
merging,
|
||||||
|
uploading,
|
||||||
|
completed,
|
||||||
|
error,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Legacy record-level sync status for models
|
||||||
|
enum RecordSyncStatus {
|
||||||
|
pending,
|
||||||
|
synced,
|
||||||
|
modified,
|
||||||
|
}
|
||||||
|
|
||||||
|
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? _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;
|
||||||
|
Function()? onSyncCompleted;
|
||||||
|
|
||||||
|
DatabaseSyncService() {
|
||||||
|
loadSavedConfiguration();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load saved configuration from SharedPreferences
|
||||||
|
Future<void> loadSavedConfiguration() async {
|
||||||
|
try {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
_serverUrl = prefs.getString(_keyServerUrl);
|
||||||
|
_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!,
|
||||||
|
password: _password!,
|
||||||
|
debug: kDebugMode,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('Error loading saved sync configuration: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save configuration to SharedPreferences
|
||||||
|
Future<void> _saveConfiguration() async {
|
||||||
|
try {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
if (_serverUrl != null) await prefs.setString(_keyServerUrl, _serverUrl!);
|
||||||
|
if (_username != null) await prefs.setString(_keyUsername, _username!);
|
||||||
|
if (_password != null) await prefs.setString(_keyPassword, _password!);
|
||||||
|
if (_configuredRemotePath != null) await prefs.setString(_keyRemotePath, _configuredRemotePath!);
|
||||||
|
} catch (e) {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('Error saving sync configuration: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void configure({
|
||||||
|
required String serverUrl,
|
||||||
|
required String username,
|
||||||
|
required String password,
|
||||||
|
required String remotePath,
|
||||||
|
}) {
|
||||||
|
// Store configuration values
|
||||||
|
_serverUrl = serverUrl;
|
||||||
|
_username = username;
|
||||||
|
_password = password;
|
||||||
|
_configuredRemotePath = remotePath;
|
||||||
|
|
||||||
|
_remotePath = remotePath.endsWith('/') ? remotePath : '$remotePath/';
|
||||||
|
|
||||||
|
_client = newClient(
|
||||||
|
serverUrl,
|
||||||
|
user: username,
|
||||||
|
password: password,
|
||||||
|
debug: kDebugMode,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Save configuration to persistent storage
|
||||||
|
_saveConfiguration();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<bool> testConnection() async {
|
||||||
|
if (_client == null) return false;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await _client!.ping();
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('Connection test failed: $e');
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> syncDatabase() async {
|
||||||
|
if (_client == null) {
|
||||||
|
throw Exception('Sync not configured');
|
||||||
|
}
|
||||||
|
|
||||||
|
_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);
|
||||||
|
onError?.call(_lastError!);
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('Sync failed: $e');
|
||||||
|
}
|
||||||
|
rethrow;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<String?> _downloadRemoteDatabase() async {
|
||||||
|
try {
|
||||||
|
// Check if remote database exists
|
||||||
|
final files = await _client!.readDir(_remotePath!);
|
||||||
|
final remoteDbExists = files.any((file) => file.name == _remoteDbFileName);
|
||||||
|
|
||||||
|
if (!remoteDbExists) {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('No remote database found, will upload local database');
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('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) {
|
||||||
|
printLog('Downloaded remote database (${remoteDbBytes.length} bytes) to: $tempDbPath');
|
||||||
|
}
|
||||||
|
|
||||||
|
return tempDbPath;
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('Failed to download remote database: $e');
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _mergeDatabases(String? remoteDbPath) async {
|
||||||
|
if (remoteDbPath == null) {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('No remote database to merge');
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('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'");
|
||||||
|
printLog('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');
|
||||||
|
printLog('Remote supplements count: ${supplementCount.first['count']}');
|
||||||
|
} catch (e) {
|
||||||
|
printLog('Error counting supplements: $e');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
final intakeCount = await remoteDb.rawQuery('SELECT COUNT(*) as count FROM supplement_intakes');
|
||||||
|
printLog('Remote intakes count: ${intakeCount.first['count']}');
|
||||||
|
} catch (e) {
|
||||||
|
printLog('Error counting intakes: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Merge supplements
|
||||||
|
await _mergeSupplements(localDb, remoteDb);
|
||||||
|
|
||||||
|
// Merge intakes
|
||||||
|
await _mergeIntakes(localDb, remoteDb);
|
||||||
|
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('Database merge completed successfully');
|
||||||
|
}
|
||||||
|
|
||||||
|
} finally {
|
||||||
|
await remoteDb.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _mergeSupplements(Database localDb, Database remoteDb) async {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('Starting supplement merge...');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get all supplements from remote database
|
||||||
|
final remoteMaps = await remoteDb.query('supplements');
|
||||||
|
final remoteSupplements =
|
||||||
|
remoteMaps.map((map) => Supplement.fromMap(map)).toList();
|
||||||
|
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog(
|
||||||
|
'Found ${remoteSupplements.length} supplements in remote database');
|
||||||
|
for (final supplement in remoteSupplements) {
|
||||||
|
printLog(
|
||||||
|
'Remote supplement: ${supplement.name} (syncId: ${supplement.syncId}, deleted: ${supplement.isDeleted})');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (final remoteSupplement in remoteSupplements) {
|
||||||
|
if (remoteSupplement.syncId.isEmpty) {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog(
|
||||||
|
'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) {
|
||||||
|
// 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) {
|
||||||
|
printLog(
|
||||||
|
'✓ Inserted new supplement: ${remoteSupplement.name}');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog(
|
||||||
|
'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);
|
||||||
|
await localDb.update(
|
||||||
|
'supplements',
|
||||||
|
supplementToUpdate.toMap(),
|
||||||
|
where: 'id = ?',
|
||||||
|
whereArgs: [existingSupplement.id],
|
||||||
|
);
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog(
|
||||||
|
'✓ Updated supplement: ${remoteSupplement.name}');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog(
|
||||||
|
'Local supplement ${remoteSupplement.name} is newer, keeping local version');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('Supplement merge completed');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _mergeIntakes(Database localDb, Database remoteDb) async {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('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) {
|
||||||
|
printLog('Found ${remoteIntakes.length} intakes in remote database');
|
||||||
|
}
|
||||||
|
|
||||||
|
for (final remoteIntake in remoteIntakes) {
|
||||||
|
if (remoteIntake.syncId.isEmpty) {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('Skipping intake - no syncId');
|
||||||
|
}
|
||||||
|
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) {
|
||||||
|
final localSupplementId = await _findLocalSupplementId(localDb, remoteIntake.supplementId, remoteDb);
|
||||||
|
if (localSupplementId != null) {
|
||||||
|
final intakeToInsert = remoteIntake.copyWith(
|
||||||
|
id: null,
|
||||||
|
supplementId: localSupplementId,
|
||||||
|
);
|
||||||
|
await localDb.insert('supplement_intakes', intakeToInsert.toMap());
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('✓ Inserted new intake: ${remoteIntake.syncId}');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('Could not find local supplement for intake ${remoteIntake.syncId}');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('Skipping deleted intake: ${remoteIntake.syncId}');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} 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(
|
||||||
|
'supplement_intakes',
|
||||||
|
intakeToUpdate.toMap(),
|
||||||
|
where: 'id = ?',
|
||||||
|
whereArgs: [existingIntake.id],
|
||||||
|
);
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('✓ Updated intake: ${remoteIntake.syncId}');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('Local intake ${remoteIntake.syncId} is newer, keeping local version');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('Intake merge completed');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<int?> _findLocalSupplementId(Database localDb, int remoteSupplementId, Database remoteDb) async {
|
||||||
|
// Get the remote supplement
|
||||||
|
final remoteSupplementMaps = await remoteDb.query(
|
||||||
|
'supplements',
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _uploadLocalDatabase() async {
|
||||||
|
try {
|
||||||
|
// Get the local database path
|
||||||
|
final localDb = await _databaseHelper.database;
|
||||||
|
final dbPath = localDb.path;
|
||||||
|
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('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) {
|
||||||
|
printLog('Database file size: ${dbBytes.length} bytes');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dbBytes.isEmpty) {
|
||||||
|
throw Exception('Database file is empty');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure remote directory exists
|
||||||
|
try {
|
||||||
|
await _client!.readDir(_remotePath!);
|
||||||
|
} catch (e) {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('Creating remote directory: $_remotePath');
|
||||||
|
}
|
||||||
|
await _client!.mkdir(_remotePath!);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upload the database file
|
||||||
|
final remoteUrl = '$_remotePath$_remoteDbFileName';
|
||||||
|
await _client!.write(remoteUrl, dbBytes);
|
||||||
|
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('Successfully uploaded database (${dbBytes.length} bytes) to: $remoteUrl');
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('Failed to upload database: $e');
|
||||||
|
}
|
||||||
|
rethrow;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _setStatus(SyncStatus status) {
|
||||||
|
_status = status;
|
||||||
|
onStatusChanged?.call(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
void clearError() {
|
||||||
|
_lastError = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
92
lib/services/notification_debug_store.dart
Normal file
92
lib/services/notification_debug_store.dart
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
class NotificationLogEntry {
|
||||||
|
final int id;
|
||||||
|
final String kind; // 'daily' | 'snooze'
|
||||||
|
final String type; // 'single' | 'group'
|
||||||
|
final int whenEpochMs; // exact scheduled time (epoch ms)
|
||||||
|
final int createdAtEpochMs; // when we created the schedule (epoch ms)
|
||||||
|
final String title;
|
||||||
|
final String payload;
|
||||||
|
final int? singleId; // supplement id for single
|
||||||
|
final String? timeKey; // HH:mm for group
|
||||||
|
|
||||||
|
const NotificationLogEntry({
|
||||||
|
required this.id,
|
||||||
|
required this.kind,
|
||||||
|
required this.type,
|
||||||
|
required this.whenEpochMs,
|
||||||
|
required this.createdAtEpochMs,
|
||||||
|
required this.title,
|
||||||
|
required this.payload,
|
||||||
|
this.singleId,
|
||||||
|
this.timeKey,
|
||||||
|
});
|
||||||
|
|
||||||
|
Map<String, dynamic> toJson() => {
|
||||||
|
'id': id,
|
||||||
|
'kind': kind,
|
||||||
|
'type': type,
|
||||||
|
'when': whenEpochMs,
|
||||||
|
'createdAt': createdAtEpochMs,
|
||||||
|
'title': title,
|
||||||
|
'payload': payload,
|
||||||
|
'singleId': singleId,
|
||||||
|
'timeKey': timeKey,
|
||||||
|
};
|
||||||
|
|
||||||
|
static NotificationLogEntry fromJson(Map<String, dynamic> map) {
|
||||||
|
return NotificationLogEntry(
|
||||||
|
id: map['id'] is int ? map['id'] as int : int.tryParse('${map['id']}') ?? 0,
|
||||||
|
kind: map['kind'] ?? 'unknown',
|
||||||
|
type: map['type'] ?? 'unknown',
|
||||||
|
whenEpochMs: map['when'] is int ? map['when'] as int : int.tryParse('${map['when']}') ?? 0,
|
||||||
|
createdAtEpochMs: map['createdAt'] is int ? map['createdAt'] as int : int.tryParse('${map['createdAt']}') ?? 0,
|
||||||
|
title: map['title'] ?? '',
|
||||||
|
payload: map['payload'] ?? '',
|
||||||
|
singleId: map['singleId'],
|
||||||
|
timeKey: map['timeKey'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class NotificationDebugStore {
|
||||||
|
NotificationDebugStore._internal();
|
||||||
|
static final NotificationDebugStore instance = NotificationDebugStore._internal();
|
||||||
|
|
||||||
|
static const String _prefsKey = 'notification_log';
|
||||||
|
static const int _maxEntries = 200;
|
||||||
|
|
||||||
|
Future<List<NotificationLogEntry>> getAll() async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final raw = prefs.getString(_prefsKey);
|
||||||
|
if (raw == null || raw.isEmpty) return [];
|
||||||
|
try {
|
||||||
|
final list = jsonDecode(raw) as List;
|
||||||
|
return list
|
||||||
|
.map((e) => NotificationLogEntry.fromJson(e as Map<String, dynamic>))
|
||||||
|
.toList();
|
||||||
|
} catch (_) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> add(NotificationLogEntry entry) async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final current = await getAll();
|
||||||
|
current.add(entry);
|
||||||
|
// Cap size
|
||||||
|
final trimmed = current.length > _maxEntries
|
||||||
|
? current.sublist(current.length - _maxEntries)
|
||||||
|
: current;
|
||||||
|
final serialized = jsonEncode(trimmed.map((e) => e.toJson()).toList());
|
||||||
|
await prefs.setString(_prefsKey, serialized);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> clear() async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.remove(_prefsKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
290
lib/services/notification_router.dart
Normal file
290
lib/services/notification_router.dart
Normal file
@@ -0,0 +1,290 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||||
|
import 'package:provider/provider.dart';
|
||||||
|
import 'package:supplements/logging.dart';
|
||||||
|
|
||||||
|
import '../models/supplement.dart';
|
||||||
|
import '../providers/supplement_provider.dart';
|
||||||
|
import '../widgets/dialogs/bulk_take_dialog.dart';
|
||||||
|
import '../widgets/dialogs/take_supplement_dialog.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:supplements/services/simple_notification_service.dart';
|
||||||
|
|
||||||
|
/// Centralizes routing from notification actions/taps to in-app UI.
|
||||||
|
/// Handles both foreground/background taps and terminated-launch scenarios.
|
||||||
|
class NotificationRouter {
|
||||||
|
NotificationRouter._internal();
|
||||||
|
static final NotificationRouter instance = NotificationRouter._internal();
|
||||||
|
|
||||||
|
GlobalKey<NavigatorState>? _navigatorKey;
|
||||||
|
|
||||||
|
void initialize(GlobalKey<NavigatorState> navigatorKey) {
|
||||||
|
_navigatorKey = navigatorKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> handleNotificationResponse(NotificationResponse response) async {
|
||||||
|
final payloadMap = _decodePayload(response.payload);
|
||||||
|
final actionId = response.actionId;
|
||||||
|
printLog('🔔 handleNotificationResponse: actionId=$actionId payload=${response.payload} map=$payloadMap');
|
||||||
|
printLog('🔔 handleNotificationResponse: Received actionId: $actionId');
|
||||||
|
printLog('🔔 handleNotificationResponse: Decoded payloadMap: $payloadMap');
|
||||||
|
|
||||||
|
// Handle Snooze actions without surfacing UI
|
||||||
|
if (actionId == 'snooze_single' || actionId == 'snooze_group') {
|
||||||
|
try {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final minutes = prefs.getInt('snooze_minutes') ?? 10;
|
||||||
|
await _scheduleSnoozeFromPayload(payloadMap, Duration(minutes: minutes));
|
||||||
|
} catch (e) {
|
||||||
|
printLog('⚠️ Failed to handle snooze action: $e');
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default: route to in-app UI for Take actions and normal taps
|
||||||
|
await _routeFromPayload(payloadMap);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> handleAppLaunchDetails(NotificationAppLaunchDetails? details) async {
|
||||||
|
if (details == null) return;
|
||||||
|
if (!details.didNotificationLaunchApp) return;
|
||||||
|
|
||||||
|
final resp = details.notificationResponse;
|
||||||
|
final payloadMap = _decodePayload(resp?.payload);
|
||||||
|
printLog('🚀 App launched from notification: payload=${resp?.payload} map=$payloadMap');
|
||||||
|
|
||||||
|
await _routeFromPayload(payloadMap);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic>? _decodePayload(String? payload) {
|
||||||
|
if (payload == null || payload.isEmpty) return null;
|
||||||
|
|
||||||
|
// Try JSON first
|
||||||
|
try {
|
||||||
|
final map = jsonDecode(payload);
|
||||||
|
if (map is Map<String, dynamic>) return map;
|
||||||
|
} catch (_) {
|
||||||
|
// Ignore and try fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback: previous implementation used HH:mm as raw payload
|
||||||
|
final hhmm = RegExp(r'^\d{2}:\d{2}$');
|
||||||
|
if (hhmm.hasMatch(payload)) {
|
||||||
|
return { 'type': 'group', 'time': payload };
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _routeFromPayload(Map<String, dynamic>? payload) async {
|
||||||
|
if (_navigatorKey == null) {
|
||||||
|
printLog('⚠️ NotificationRouter not initialized with navigatorKey');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait until navigator is ready and providers have loaded
|
||||||
|
final ready = await _waitUntilReady(timeout: const Duration(seconds: 5));
|
||||||
|
if (!ready) {
|
||||||
|
printLog('⚠️ Timeout waiting for app to be ready for routing');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final context = _navigatorKey!.currentContext!;
|
||||||
|
final provider = context.read<SupplementProvider>();
|
||||||
|
|
||||||
|
if (payload == null) {
|
||||||
|
printLog('⚠️ No payload to route');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final type = payload['type'];
|
||||||
|
if (type == 'single') {
|
||||||
|
final id = payload['id'];
|
||||||
|
if (id is int) {
|
||||||
|
Supplement? s;
|
||||||
|
try {
|
||||||
|
s = provider.supplements.firstWhere((el) => el.id == id);
|
||||||
|
} catch (_) {
|
||||||
|
s = null;
|
||||||
|
}
|
||||||
|
if (s == null) {
|
||||||
|
// Attempt reload once
|
||||||
|
await provider.loadSupplements();
|
||||||
|
try {
|
||||||
|
s = provider.supplements.firstWhere((el) => el.id == id);
|
||||||
|
} catch (_) {
|
||||||
|
s = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (s != null) {
|
||||||
|
// For single: use the regular dialog (with time selection)
|
||||||
|
// Ensure we close any existing dialog first
|
||||||
|
_popAnyDialog(context);
|
||||||
|
await showTakeSupplementDialog(context, s, hideTime: false);
|
||||||
|
} else {
|
||||||
|
printLog('⚠️ Supplement id=$id not found for single-take routing');
|
||||||
|
_showSnack(context, 'Supplement not found');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (type == 'group') {
|
||||||
|
final timeKey = payload['time'];
|
||||||
|
if (timeKey is String) {
|
||||||
|
// Build list of supplements scheduled at this timeKey
|
||||||
|
final List<Supplement> list = provider.supplements.where((s) {
|
||||||
|
return s.isActive && s.reminderTimes.contains(timeKey);
|
||||||
|
}).toList();
|
||||||
|
|
||||||
|
if (list.isEmpty) {
|
||||||
|
printLog('⚠️ No supplements found for group time=$timeKey');
|
||||||
|
_showSnack(context, 'No supplements for $timeKey');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_popAnyDialog(context);
|
||||||
|
await showBulkTakeDialog(context, list);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
printLog('⚠️ Unknown payload type: $type');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _scheduleSnoozeFromPayload(Map<String, dynamic>? payload, Duration delay) async {
|
||||||
|
if (payload == null) {
|
||||||
|
printLog('⚠️ Snooze requested but payload was null');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try to wait for providers to be ready to build rich content.
|
||||||
|
final ready = await _waitUntilReady(timeout: const Duration(seconds: 5));
|
||||||
|
BuildContext? ctx = _navigatorKey?.currentContext;
|
||||||
|
|
||||||
|
SupplementProvider? provider;
|
||||||
|
if (ready && ctx != null) {
|
||||||
|
provider = Provider.of<SupplementProvider>(ctx, listen: false);
|
||||||
|
}
|
||||||
|
|
||||||
|
String title = 'Supplement reminder';
|
||||||
|
String body = 'Tap to see details';
|
||||||
|
bool isSingle = false;
|
||||||
|
// Start with a mutable copy of the payload to add meta information
|
||||||
|
final Map<String, dynamic> mutablePayload = Map.from(payload);
|
||||||
|
|
||||||
|
final type = mutablePayload['type'];
|
||||||
|
|
||||||
|
if (type == 'single') {
|
||||||
|
final id = payload['id'];
|
||||||
|
isSingle = true;
|
||||||
|
// Ensure the payload for single snooze is correctly formatted
|
||||||
|
mutablePayload['type'] = 'single';
|
||||||
|
mutablePayload['id'] = id;
|
||||||
|
|
||||||
|
if (id is int && provider != null) {
|
||||||
|
Supplement? s;
|
||||||
|
try {
|
||||||
|
s = provider.supplements.firstWhere((el) => el.id == id);
|
||||||
|
} catch (_) {
|
||||||
|
s = null;
|
||||||
|
}
|
||||||
|
if (s != null) {
|
||||||
|
title = 'Time for ${s.name}';
|
||||||
|
body =
|
||||||
|
'${s.name} — ${s.numberOfUnits} ${s.unitType} (${s.ingredientsPerUnit})';
|
||||||
|
} else {
|
||||||
|
body = 'Tap to take supplement';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (type == 'group') {
|
||||||
|
final timeKey = mutablePayload['time'];
|
||||||
|
if (timeKey is String) {
|
||||||
|
if (provider != null) {
|
||||||
|
final list = provider.supplements
|
||||||
|
.where((s) =>
|
||||||
|
s.isActive && s.reminderTimes.contains(timeKey))
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
if (list.length == 1) {
|
||||||
|
final s = list.first;
|
||||||
|
isSingle = true;
|
||||||
|
title = 'Time for ${s.name}';
|
||||||
|
body =
|
||||||
|
'${s.name} — ${s.numberOfUnits} ${s.unitType} (${s.ingredientsPerUnit})';
|
||||||
|
// If a group becomes a single, update the payload type
|
||||||
|
mutablePayload['type'] = 'single';
|
||||||
|
mutablePayload['id'] = s.id;
|
||||||
|
mutablePayload.remove('time'); // Remove time key for single
|
||||||
|
} else if (list.isNotEmpty) {
|
||||||
|
isSingle = false;
|
||||||
|
title = 'Time for ${list.length} supplements';
|
||||||
|
final lines = list
|
||||||
|
.map((s) =>
|
||||||
|
'${s.name} — ${s.numberOfUnits} ${s.unitType} (${s.ingredientsPerUnit})')
|
||||||
|
.toList();
|
||||||
|
body = lines.join('\n');
|
||||||
|
// Ensure payload type is group
|
||||||
|
mutablePayload['type'] = 'group';
|
||||||
|
mutablePayload['time'] = timeKey;
|
||||||
|
} else {
|
||||||
|
// Fallback generic group
|
||||||
|
isSingle = false;
|
||||||
|
title = 'Supplement reminder';
|
||||||
|
body = 'Tap to see details';
|
||||||
|
mutablePayload['type'] = 'group';
|
||||||
|
mutablePayload['time'] = timeKey;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Provider not ready; schedule generic group payload
|
||||||
|
isSingle = false;
|
||||||
|
mutablePayload['type'] = 'group';
|
||||||
|
mutablePayload['time'] = timeKey;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure the payload always has the correct type and ID/time for logging
|
||||||
|
// and re-scheduling. The SimpleNotificationService will add the 'meta' field.
|
||||||
|
final payloadStr = jsonEncode(mutablePayload);
|
||||||
|
|
||||||
|
await SimpleNotificationService.instance.scheduleOneOffReminder(
|
||||||
|
title: title,
|
||||||
|
body: body,
|
||||||
|
payload: payloadStr,
|
||||||
|
isSingle: isSingle,
|
||||||
|
delay: delay,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<bool> _waitUntilReady({required Duration timeout}) async {
|
||||||
|
final start = DateTime.now();
|
||||||
|
while (DateTime.now().difference(start) < timeout) {
|
||||||
|
final key = _navigatorKey;
|
||||||
|
final ctx = key?.currentContext;
|
||||||
|
if (ctx != null) {
|
||||||
|
try {
|
||||||
|
final provider = Provider.of<SupplementProvider>(ctx, listen: false);
|
||||||
|
if (!provider.isLoading) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
} catch (_) {
|
||||||
|
// Provider not available yet
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await Future.delayed(const Duration(milliseconds: 100));
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void _popAnyDialog(BuildContext context) {
|
||||||
|
if (Navigator.of(context, rootNavigator: true).canPop()) {
|
||||||
|
Navigator.of(context, rootNavigator: true).pop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _showSnack(BuildContext context, String message) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text(message)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,688 +1,11 @@
|
|||||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
/*
|
||||||
import 'package:timezone/timezone.dart' as tz;
|
Deprecated/removed: notification_service.dart
|
||||||
import 'package:timezone/data/latest.dart' as tz;
|
|
||||||
import '../models/supplement.dart';
|
|
||||||
import 'database_helper.dart';
|
|
||||||
|
|
||||||
// Top-level function to handle notification responses when app is running
|
This legacy notification service has been intentionally removed.
|
||||||
@pragma('vm:entry-point')
|
The app now uses a minimal scheduler in:
|
||||||
void notificationTapBackground(NotificationResponse notificationResponse) {
|
services/simple_notification_service.dart
|
||||||
print('📱 === BACKGROUND NOTIFICATION RESPONSE ===');
|
|
||||||
print('📱 Action ID: ${notificationResponse.actionId}');
|
|
||||||
print('📱 Payload: ${notificationResponse.payload}');
|
|
||||||
print('📱 Notification ID: ${notificationResponse.id}');
|
|
||||||
print('📱 ==========================================');
|
|
||||||
|
|
||||||
// For now, just log the action. The main app handler will process it.
|
All retry/snooze/database-tracking logic has been dropped to keep things simple.
|
||||||
if (notificationResponse.actionId == 'take_supplement') {
|
This file is left empty to ensure any lingering references fail at compile time,
|
||||||
print('📱 BACKGROUND: Take action detected');
|
prompting migration to the new SimpleNotificationService.
|
||||||
} else if (notificationResponse.actionId == 'snooze_10') {
|
*/
|
||||||
print('📱 BACKGROUND: Snooze action detected');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class NotificationService {
|
|
||||||
static final NotificationService _instance = NotificationService._internal();
|
|
||||||
factory NotificationService() => _instance;
|
|
||||||
NotificationService._internal();
|
|
||||||
|
|
||||||
final FlutterLocalNotificationsPlugin _notifications = FlutterLocalNotificationsPlugin();
|
|
||||||
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;
|
|
||||||
|
|
||||||
// Set callback for handling supplement intake from notifications
|
|
||||||
void setTakeSupplementCallback(Function(int supplementId, String supplementName, double units, String unitType) callback) {
|
|
||||||
_onTakeSupplementCallback = callback;
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> initialize() async {
|
|
||||||
print('📱 Initializing NotificationService...');
|
|
||||||
if (_isInitialized) {
|
|
||||||
print('📱 Already initialized');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
print('📱 Initializing timezones...');
|
|
||||||
print('📱 Engine initialized flag: $_engineInitialized');
|
|
||||||
|
|
||||||
if (!_engineInitialized) {
|
|
||||||
tz.initializeTimeZones();
|
|
||||||
_engineInitialized = true;
|
|
||||||
print('📱 Timezones initialized successfully');
|
|
||||||
} else {
|
|
||||||
print('📱 Timezones already initialized, skipping');
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
print('📱 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('📱 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
|
|
||||||
} else if (timeZoneName.contains('UTC') || timeZoneName.contains('GMT')) {
|
|
||||||
location = tz.getLocation('UTC');
|
|
||||||
} else {
|
|
||||||
// Fallback: try to use the timezone name directly
|
|
||||||
try {
|
|
||||||
location = tz.getLocation(timeZoneName);
|
|
||||||
} catch (e) {
|
|
||||||
print('📱 Could not find timezone $timeZoneName, using Europe/Amsterdam as default');
|
|
||||||
location = tz.getLocation('Europe/Amsterdam');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tz.setLocalLocation(location);
|
|
||||||
print('📱 Timezone set to: ${location.name}');
|
|
||||||
|
|
||||||
} catch (e) {
|
|
||||||
print('📱 Error setting timezone: $e, using default');
|
|
||||||
// Fallback to a reasonable default for Netherlands
|
|
||||||
tz.setLocalLocation(tz.getLocation('Europe/Amsterdam'));
|
|
||||||
}
|
|
||||||
|
|
||||||
print('📱 Current local time: ${tz.TZDateTime.now(tz.local)}');
|
|
||||||
print('📱 Current system time: ${DateTime.now()}');
|
|
||||||
|
|
||||||
const AndroidInitializationSettings androidSettings = AndroidInitializationSettings('@mipmap/ic_launcher');
|
|
||||||
const DarwinInitializationSettings iosSettings = DarwinInitializationSettings(
|
|
||||||
requestAlertPermission: false, // We'll request these separately
|
|
||||||
requestBadgePermission: false,
|
|
||||||
requestSoundPermission: false,
|
|
||||||
);
|
|
||||||
const LinuxInitializationSettings linuxSettings = LinuxInitializationSettings(
|
|
||||||
defaultActionName: 'Open notification',
|
|
||||||
);
|
|
||||||
|
|
||||||
const InitializationSettings initSettings = InitializationSettings(
|
|
||||||
android: androidSettings,
|
|
||||||
iOS: iosSettings,
|
|
||||||
linux: linuxSettings,
|
|
||||||
);
|
|
||||||
|
|
||||||
print('📱 Initializing flutter_local_notifications...');
|
|
||||||
await _notifications.initialize(
|
|
||||||
initSettings,
|
|
||||||
onDidReceiveNotificationResponse: _onNotificationResponse,
|
|
||||||
onDidReceiveBackgroundNotificationResponse: notificationTapBackground,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Test if notification response callback is working
|
|
||||||
print('📱 Callback function is set and ready');
|
|
||||||
|
|
||||||
_isInitialized = true;
|
|
||||||
print('📱 NotificationService initialization complete');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle notification responses (when user taps on notification or action)
|
|
||||||
void _onNotificationResponse(NotificationResponse response) {
|
|
||||||
print('📱 === NOTIFICATION RESPONSE ===');
|
|
||||||
print('📱 Action ID: ${response.actionId}');
|
|
||||||
print('📱 Payload: ${response.payload}');
|
|
||||||
print('📱 Notification ID: ${response.id}');
|
|
||||||
print('📱 Input: ${response.input}');
|
|
||||||
print('📱 ===============================');
|
|
||||||
|
|
||||||
if (response.actionId == 'take_supplement') {
|
|
||||||
print('📱 Processing TAKE action...');
|
|
||||||
_handleTakeAction(response.payload, response.id);
|
|
||||||
} else if (response.actionId == 'snooze_10') {
|
|
||||||
print('📱 Processing SNOOZE action...');
|
|
||||||
_handleSnoozeAction(response.payload, 10, response.id);
|
|
||||||
} else {
|
|
||||||
print('📱 Default notification tap (no specific action)');
|
|
||||||
// Default tap (no actionId) opens the app normally
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _handleTakeAction(String? payload, int? notificationId) async {
|
|
||||||
print('📱 === HANDLING TAKE ACTION ===');
|
|
||||||
print('📱 Payload received: $payload');
|
|
||||||
|
|
||||||
if (payload != null) {
|
|
||||||
try {
|
|
||||||
// Parse the payload to get supplement info
|
|
||||||
final parts = payload.split('|');
|
|
||||||
print('📱 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('📱 Parsed data:');
|
|
||||||
print('📱 - ID: $supplementId');
|
|
||||||
print('📱 - Name: $supplementName');
|
|
||||||
print('📱 - Units: $units');
|
|
||||||
print('📱 - Type: $unitType');
|
|
||||||
|
|
||||||
// Call the callback to record the intake
|
|
||||||
if (_onTakeSupplementCallback != null) {
|
|
||||||
print('📱 Calling supplement callback...');
|
|
||||||
_onTakeSupplementCallback!(supplementId, supplementName, units, unitType);
|
|
||||||
print('📱 Callback completed');
|
|
||||||
} else {
|
|
||||||
print('📱 ERROR: No callback registered!');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mark notification as taken in database (this will cancel any pending retries)
|
|
||||||
if (notificationId != null) {
|
|
||||||
print('📱 Marking notification $notificationId as taken');
|
|
||||||
await DatabaseHelper.instance.markNotificationTaken(notificationId);
|
|
||||||
|
|
||||||
// Cancel any pending retry notifications for this notification
|
|
||||||
_cancelRetryNotifications(notificationId);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Show a confirmation notification
|
|
||||||
print('📱 Showing confirmation notification...');
|
|
||||||
showInstantNotification(
|
|
||||||
'Supplement Taken!',
|
|
||||||
'$supplementName has been recorded at ${DateTime.now().hour.toString().padLeft(2, '0')}:${DateTime.now().minute.toString().padLeft(2, '0')}',
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
print('📱 ERROR: Invalid payload format - not enough parts');
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
print('📱 ERROR in _handleTakeAction: $e');
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
print('📱 ERROR: Payload is null');
|
|
||||||
}
|
|
||||||
print('📱 === TAKE ACTION COMPLETE ===');
|
|
||||||
}
|
|
||||||
|
|
||||||
void _cancelRetryNotifications(int notificationId) {
|
|
||||||
// Retry notifications use ID range starting from 200000
|
|
||||||
for (int i = 0; i < 10; i++) { // Cancel up to 10 potential retries
|
|
||||||
int retryId = 200000 + (notificationId * 10) + i;
|
|
||||||
_notifications.cancel(retryId);
|
|
||||||
print('📱 Cancelled retry notification ID: $retryId');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void _handleSnoozeAction(String? payload, int minutes, int? notificationId) {
|
|
||||||
print('📱 === HANDLING SNOOZE ACTION ===');
|
|
||||||
print('📱 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('📱 Snoozing supplement for $minutes minutes: $supplementName');
|
|
||||||
|
|
||||||
// Mark notification as snoozed in database (increment retry count)
|
|
||||||
if (notificationId != null) {
|
|
||||||
print('📱 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('📱 Snooze time: $snoozeTime');
|
|
||||||
|
|
||||||
_notifications.zonedSchedule(
|
|
||||||
supplementId * 1000 + minutes, // Unique ID for snooze notifications
|
|
||||||
'Reminder: $supplementName',
|
|
||||||
'Snoozed reminder - Take your $supplementName now',
|
|
||||||
snoozeTime,
|
|
||||||
NotificationDetails(
|
|
||||||
android: AndroidNotificationDetails(
|
|
||||||
'supplement_reminders',
|
|
||||||
'Supplement Reminders',
|
|
||||||
channelDescription: 'Notifications for supplement intake reminders',
|
|
||||||
importance: Importance.high,
|
|
||||||
priority: Priority.high,
|
|
||||||
actions: [
|
|
||||||
AndroidNotificationAction(
|
|
||||||
'take_supplement',
|
|
||||||
'Take',
|
|
||||||
),
|
|
||||||
AndroidNotificationAction(
|
|
||||||
'snooze_10',
|
|
||||||
'Snooze 10min',
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
iOS: const DarwinNotificationDetails(),
|
|
||||||
),
|
|
||||||
androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
|
|
||||||
payload: payload,
|
|
||||||
);
|
|
||||||
|
|
||||||
showInstantNotification(
|
|
||||||
'Reminder Snoozed',
|
|
||||||
'$supplementName reminder snoozed for $minutes minutes',
|
|
||||||
);
|
|
||||||
print('📱 Snooze scheduled successfully');
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
print('📱 Error handling snooze action: $e');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
print('📱 === SNOOZE ACTION COMPLETE ===');
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Check for persistent reminders from app context with settings
|
|
||||||
Future<void> checkPersistentReminders(
|
|
||||||
bool persistentReminders,
|
|
||||||
int reminderRetryInterval,
|
|
||||||
int maxRetryAttempts,
|
|
||||||
) async {
|
|
||||||
await schedulePersistentReminders(
|
|
||||||
persistentReminders: persistentReminders,
|
|
||||||
reminderRetryInterval: reminderRetryInterval,
|
|
||||||
maxRetryAttempts: maxRetryAttempts,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Check for pending notifications that need retry and schedule them
|
|
||||||
Future<void> schedulePersistentReminders({
|
|
||||||
required bool persistentReminders,
|
|
||||||
required int reminderRetryInterval,
|
|
||||||
required int maxRetryAttempts,
|
|
||||||
}) async {
|
|
||||||
print('📱 Checking for pending notifications to retry...');
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (!persistentReminders) {
|
|
||||||
print('📱 Persistent reminders disabled');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
print('📱 Retry settings: interval=$reminderRetryInterval min, max=$maxRetryAttempts attempts');
|
|
||||||
|
|
||||||
// Get all pending notifications from database
|
|
||||||
final pendingNotifications = await DatabaseHelper.instance.getPendingNotifications();
|
|
||||||
print('📱 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
|
|
||||||
? DateTime.parse(notification['lastRetryTime']).toLocal()
|
|
||||||
: null;
|
|
||||||
|
|
||||||
// Check if notification is overdue
|
|
||||||
final timeSinceScheduled = now.difference(scheduledTime).inMinutes;
|
|
||||||
final shouldRetry = timeSinceScheduled >= reminderRetryInterval;
|
|
||||||
|
|
||||||
print('📱 Checking notification ${notification['notificationId']}:');
|
|
||||||
print('📱 Scheduled: $scheduledTime (local)');
|
|
||||||
print('📱 Now: $now');
|
|
||||||
print('📱 Time since scheduled: $timeSinceScheduled minutes');
|
|
||||||
print('📱 Retry interval: $reminderRetryInterval minutes');
|
|
||||||
print('📱 Should retry: $shouldRetry');
|
|
||||||
print('📱 Retry count: $retryCount / $maxRetryAttempts');
|
|
||||||
|
|
||||||
// Check if we haven't exceeded max retry attempts
|
|
||||||
if (retryCount >= maxRetryAttempts) {
|
|
||||||
print('📱 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;
|
|
||||||
if (timeSinceLastRetry < reminderRetryInterval) {
|
|
||||||
print('📱 Notification ${notification['notificationId']} not ready for retry yet');
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (shouldRetry) {
|
|
||||||
print('📱 ⚡ SCHEDULING RETRY for notification ${notification['notificationId']}');
|
|
||||||
await _scheduleRetryNotification(notification, retryCount + 1);
|
|
||||||
} else {
|
|
||||||
print('📱 ⏸️ NOT READY FOR RETRY: ${notification['notificationId']}');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
print('📱 Error scheduling persistent reminders: $e');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _scheduleRetryNotification(Map<String, dynamic> notification, int retryAttempt) async {
|
|
||||||
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('📱 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,
|
|
||||||
'Reminder: ${supplement.name}',
|
|
||||||
'Don\'t forget to take your ${supplement.name}! (Retry #$retryAttempt)',
|
|
||||||
NotificationDetails(
|
|
||||||
android: AndroidNotificationDetails(
|
|
||||||
'supplement_reminders',
|
|
||||||
'Supplement Reminders',
|
|
||||||
channelDescription: 'Notifications for supplement intake reminders',
|
|
||||||
importance: Importance.high,
|
|
||||||
priority: Priority.high,
|
|
||||||
actions: [
|
|
||||||
AndroidNotificationAction(
|
|
||||||
'take_supplement',
|
|
||||||
'Take',
|
|
||||||
showsUserInterface: true,
|
|
||||||
),
|
|
||||||
AndroidNotificationAction(
|
|
||||||
'snooze_10',
|
|
||||||
'Snooze 10min',
|
|
||||||
showsUserInterface: true,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
iOS: const DarwinNotificationDetails(),
|
|
||||||
),
|
|
||||||
payload: '${supplement.id}|${supplement.name}|${supplement.numberOfUnits}|${supplement.unitType}|$notificationId',
|
|
||||||
);
|
|
||||||
|
|
||||||
// Update the retry count in database
|
|
||||||
await DatabaseHelper.instance.incrementRetryCount(notificationId);
|
|
||||||
|
|
||||||
print('📱 Retry notification scheduled successfully');
|
|
||||||
} catch (e) {
|
|
||||||
print('📱 Error scheduling retry notification: $e');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<bool> requestPermissions() async {
|
|
||||||
print('📱 Requesting notification permissions...');
|
|
||||||
if (_permissionsRequested) {
|
|
||||||
print('📱 Permissions already requested');
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
_permissionsRequested = true;
|
|
||||||
|
|
||||||
final androidPlugin = _notifications.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>();
|
|
||||||
if (androidPlugin != null) {
|
|
||||||
print('📱 Requesting Android permissions...');
|
|
||||||
final granted = await androidPlugin.requestNotificationsPermission();
|
|
||||||
print('📱 Android permissions granted: $granted');
|
|
||||||
if (granted != true) {
|
|
||||||
_permissionsRequested = false;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
final iosPlugin = _notifications.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>();
|
|
||||||
if (iosPlugin != null) {
|
|
||||||
print('📱 Requesting iOS permissions...');
|
|
||||||
final granted = await iosPlugin.requestPermissions(
|
|
||||||
alert: true,
|
|
||||||
badge: true,
|
|
||||||
sound: true,
|
|
||||||
);
|
|
||||||
print('📱 iOS permissions granted: $granted');
|
|
||||||
if (granted != true) {
|
|
||||||
_permissionsRequested = false;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
print('📱 All permissions granted successfully');
|
|
||||||
return true;
|
|
||||||
} catch (e) {
|
|
||||||
_permissionsRequested = false;
|
|
||||||
print('📱 Error requesting permissions: $e');
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> scheduleSupplementReminders(Supplement supplement) async {
|
|
||||||
print('📱 Scheduling reminders for ${supplement.name}');
|
|
||||||
print('📱 Reminder times: ${supplement.reminderTimes}');
|
|
||||||
|
|
||||||
// Cancel existing notifications for this supplement
|
|
||||||
await cancelSupplementReminders(supplement.id!);
|
|
||||||
|
|
||||||
for (int i = 0; i < supplement.reminderTimes.length; i++) {
|
|
||||||
final timeStr = supplement.reminderTimes[i];
|
|
||||||
final timeParts = timeStr.split(':');
|
|
||||||
final hour = int.parse(timeParts[0]);
|
|
||||||
final minute = int.parse(timeParts[1]);
|
|
||||||
|
|
||||||
final notificationId = supplement.id! * 100 + i; // Unique ID for each reminder
|
|
||||||
final scheduledTime = _nextInstanceOfTime(hour, minute);
|
|
||||||
|
|
||||||
print('📱 Scheduling notification ID $notificationId for ${timeStr} -> ${scheduledTime}');
|
|
||||||
|
|
||||||
// Track this notification in the database
|
|
||||||
await DatabaseHelper.instance.trackNotification(
|
|
||||||
notificationId: notificationId,
|
|
||||||
supplementId: supplement.id!,
|
|
||||||
scheduledTime: scheduledTime.toLocal(),
|
|
||||||
);
|
|
||||||
|
|
||||||
await _notifications.zonedSchedule(
|
|
||||||
notificationId,
|
|
||||||
'Time for ${supplement.name}',
|
|
||||||
'Take ${supplement.numberOfUnits} ${supplement.unitType} (${supplement.ingredientsPerUnit})',
|
|
||||||
scheduledTime,
|
|
||||||
NotificationDetails(
|
|
||||||
android: AndroidNotificationDetails(
|
|
||||||
'supplement_reminders',
|
|
||||||
'Supplement Reminders',
|
|
||||||
channelDescription: 'Notifications for supplement intake reminders',
|
|
||||||
importance: Importance.high,
|
|
||||||
priority: Priority.high,
|
|
||||||
actions: [
|
|
||||||
AndroidNotificationAction(
|
|
||||||
'take_supplement',
|
|
||||||
'Take',
|
|
||||||
icon: DrawableResourceAndroidBitmap('@android:drawable/ic_menu_save'),
|
|
||||||
showsUserInterface: true, // Changed to true to open app
|
|
||||||
),
|
|
||||||
AndroidNotificationAction(
|
|
||||||
'snooze_10',
|
|
||||||
'Snooze 10min',
|
|
||||||
icon: DrawableResourceAndroidBitmap('@android:drawable/ic_menu_recent_history'),
|
|
||||||
showsUserInterface: true, // Changed to true to open app
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
iOS: const DarwinNotificationDetails(),
|
|
||||||
),
|
|
||||||
androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
|
|
||||||
matchDateTimeComponents: DateTimeComponents.time,
|
|
||||||
payload: '${supplement.id}|${supplement.name}|${supplement.numberOfUnits}|${supplement.unitType}',
|
|
||||||
);
|
|
||||||
|
|
||||||
print('📱 Successfully scheduled notification ID $notificationId');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get all pending notifications to verify
|
|
||||||
final pendingNotifications = await _notifications.pendingNotificationRequests();
|
|
||||||
print('📱 Total pending notifications: ${pendingNotifications.length}');
|
|
||||||
for (final notification in pendingNotifications) {
|
|
||||||
print('📱 Pending: ID=${notification.id}, Title=${notification.title}');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> cancelSupplementReminders(int supplementId) async {
|
|
||||||
// Cancel all notifications for this supplement (up to 10 possible reminders)
|
|
||||||
for (int i = 0; i < 10; i++) {
|
|
||||||
final notificationId = supplementId * 100 + i;
|
|
||||||
await _notifications.cancel(notificationId);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Also clean up database tracking records for this supplement
|
|
||||||
await DatabaseHelper.instance.clearNotificationTracking(supplementId);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> cancelAllReminders() async {
|
|
||||||
await _notifications.cancelAll();
|
|
||||||
}
|
|
||||||
|
|
||||||
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('📱 Current time: $now (${now.timeZoneName})');
|
|
||||||
print('📱 Target time: ${hour.toString().padLeft(2, '0')}:${minute.toString().padLeft(2, '0')}');
|
|
||||||
print('📱 Initial scheduled date: $scheduledDate (${scheduledDate.timeZoneName})');
|
|
||||||
|
|
||||||
if (scheduledDate.isBefore(now)) {
|
|
||||||
scheduledDate = scheduledDate.add(const Duration(days: 1));
|
|
||||||
print('📱 Time has passed, scheduling for tomorrow: $scheduledDate (${scheduledDate.timeZoneName})');
|
|
||||||
} else {
|
|
||||||
print('📱 Time is in the future, scheduling for today: $scheduledDate (${scheduledDate.timeZoneName})');
|
|
||||||
}
|
|
||||||
|
|
||||||
return scheduledDate;
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> showInstantNotification(String title, String body) async {
|
|
||||||
print('📱 Showing instant notification: $title - $body');
|
|
||||||
const NotificationDetails notificationDetails = NotificationDetails(
|
|
||||||
android: AndroidNotificationDetails(
|
|
||||||
'instant_notifications',
|
|
||||||
'Instant Notifications',
|
|
||||||
channelDescription: 'Instant notifications for supplement app',
|
|
||||||
importance: Importance.high,
|
|
||||||
priority: Priority.high,
|
|
||||||
),
|
|
||||||
iOS: DarwinNotificationDetails(),
|
|
||||||
);
|
|
||||||
|
|
||||||
await _notifications.show(
|
|
||||||
DateTime.now().millisecondsSinceEpoch ~/ 1000,
|
|
||||||
title,
|
|
||||||
body,
|
|
||||||
notificationDetails,
|
|
||||||
);
|
|
||||||
print('📱 Instant notification sent');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Debug function to test notifications
|
|
||||||
Future<void> testNotification() async {
|
|
||||||
print('📱 Testing notification system...');
|
|
||||||
await showInstantNotification('Test Notification', 'This is a test notification to verify the system is working.');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Debug function to schedule a test notification 1 minute from now
|
|
||||||
Future<void> testScheduledNotification() async {
|
|
||||||
print('📱 Testing scheduled notification...');
|
|
||||||
final now = tz.TZDateTime.now(tz.local);
|
|
||||||
final testTime = now.add(const Duration(minutes: 1));
|
|
||||||
|
|
||||||
print('📱 Scheduling test notification for: $testTime');
|
|
||||||
|
|
||||||
await _notifications.zonedSchedule(
|
|
||||||
99999, // Special ID for test notifications
|
|
||||||
'Test Scheduled Notification',
|
|
||||||
'This notification was scheduled 1 minute ago at ${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}',
|
|
||||||
testTime,
|
|
||||||
const NotificationDetails(
|
|
||||||
android: AndroidNotificationDetails(
|
|
||||||
'test_notifications',
|
|
||||||
'Test Notifications',
|
|
||||||
channelDescription: 'Test notifications for debugging',
|
|
||||||
importance: Importance.high,
|
|
||||||
priority: Priority.high,
|
|
||||||
),
|
|
||||||
iOS: DarwinNotificationDetails(),
|
|
||||||
),
|
|
||||||
androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
|
|
||||||
);
|
|
||||||
|
|
||||||
print('📱 Test notification scheduled successfully');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Debug function to get all pending notifications
|
|
||||||
Future<List<PendingNotificationRequest>> getPendingNotifications() async {
|
|
||||||
return await _notifications.pendingNotificationRequests();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Debug function to test notification actions
|
|
||||||
Future<void> testNotificationWithActions() async {
|
|
||||||
print('📱 Creating test notification with actions...');
|
|
||||||
|
|
||||||
await _notifications.show(
|
|
||||||
88888, // Special test ID
|
|
||||||
'Test Action Notification',
|
|
||||||
'Tap Take or Snooze to test notification actions',
|
|
||||||
NotificationDetails(
|
|
||||||
android: AndroidNotificationDetails(
|
|
||||||
'test_notifications',
|
|
||||||
'Test Notifications',
|
|
||||||
channelDescription: 'Test notifications for debugging actions',
|
|
||||||
importance: Importance.high,
|
|
||||||
priority: Priority.high,
|
|
||||||
actions: [
|
|
||||||
AndroidNotificationAction(
|
|
||||||
'take_supplement',
|
|
||||||
'Take',
|
|
||||||
icon: DrawableResourceAndroidBitmap('@android:drawable/ic_menu_save'),
|
|
||||||
showsUserInterface: true,
|
|
||||||
),
|
|
||||||
AndroidNotificationAction(
|
|
||||||
'snooze_10',
|
|
||||||
'Snooze 10min',
|
|
||||||
icon: DrawableResourceAndroidBitmap('@android:drawable/ic_menu_recent_history'),
|
|
||||||
showsUserInterface: true,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
iOS: const DarwinNotificationDetails(),
|
|
||||||
),
|
|
||||||
payload: '999|Test Supplement|1.0|capsule',
|
|
||||||
);
|
|
||||||
|
|
||||||
print('📱 Test notification with actions created');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Debug function to test basic notification tap response
|
|
||||||
Future<void> testBasicNotification() async {
|
|
||||||
print('📱 Creating basic test notification...');
|
|
||||||
|
|
||||||
await _notifications.show(
|
|
||||||
77777, // Special test ID for basic notification
|
|
||||||
'Basic Test Notification',
|
|
||||||
'Tap this notification to test basic callback',
|
|
||||||
NotificationDetails(
|
|
||||||
android: AndroidNotificationDetails(
|
|
||||||
'test_notifications',
|
|
||||||
'Test Notifications',
|
|
||||||
channelDescription: 'Test notifications for debugging',
|
|
||||||
importance: Importance.high,
|
|
||||||
priority: Priority.high,
|
|
||||||
),
|
|
||||||
iOS: const DarwinNotificationDetails(),
|
|
||||||
),
|
|
||||||
payload: 'basic_test',
|
|
||||||
);
|
|
||||||
|
|
||||||
print('📱 Basic test notification created');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
568
lib/services/simple_notification_service.dart
Normal file
568
lib/services/simple_notification_service.dart
Normal file
@@ -0,0 +1,568 @@
|
|||||||
|
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||||
|
import 'package:supplements/logging.dart';
|
||||||
|
import 'package:timezone/data/latest.dart' as tzdata;
|
||||||
|
import 'package:timezone/timezone.dart' as tz;
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'package:supplements/services/notification_router.dart';
|
||||||
|
import 'package:supplements/services/notification_debug_store.dart';
|
||||||
|
|
||||||
|
import '../models/supplement.dart';
|
||||||
|
|
||||||
|
/// A minimal notification scheduler focused purely on:
|
||||||
|
/// - Initialization
|
||||||
|
/// - Permission requests
|
||||||
|
/// - Scheduling daily notifications for supplements
|
||||||
|
/// - Canceling scheduled notifications
|
||||||
|
///
|
||||||
|
/// No retries, no snooze, no database logic.
|
||||||
|
class SimpleNotificationService {
|
||||||
|
SimpleNotificationService._internal();
|
||||||
|
static final SimpleNotificationService instance =
|
||||||
|
SimpleNotificationService._internal();
|
||||||
|
|
||||||
|
final FlutterLocalNotificationsPlugin _plugin =
|
||||||
|
FlutterLocalNotificationsPlugin();
|
||||||
|
|
||||||
|
bool _initialized = false;
|
||||||
|
|
||||||
|
// Channel IDs
|
||||||
|
static const String _channelDailyId = 'supplement_reminders';
|
||||||
|
static const String _channelDailyName = 'Supplement Reminders';
|
||||||
|
static const String _channelDailyDescription = 'Daily supplement intake reminders';
|
||||||
|
|
||||||
|
/// Initialize timezone data and the notifications plugin.
|
||||||
|
///
|
||||||
|
/// Note: This does not request runtime permissions. Call [requestPermissions]
|
||||||
|
/// to prompt the user for notification permissions.
|
||||||
|
Future<void> initialize({
|
||||||
|
DidReceiveBackgroundNotificationResponseCallback? onDidReceiveBackgroundNotificationResponse,
|
||||||
|
}) async {
|
||||||
|
if (_initialized) return;
|
||||||
|
|
||||||
|
// Initialize timezone database and set a sane default.
|
||||||
|
// If you prefer, replace 'Europe/Amsterdam' with your preferred default,
|
||||||
|
// or integrate a platform timezone resolver.
|
||||||
|
tzdata.initializeTimeZones();
|
||||||
|
tz.setLocalLocation(tz.getLocation('Europe/Amsterdam'));
|
||||||
|
|
||||||
|
const androidSettings = AndroidInitializationSettings('@mipmap/ic_launcher');
|
||||||
|
final iosSettings = DarwinInitializationSettings(
|
||||||
|
requestAlertPermission: false,
|
||||||
|
requestBadgePermission: false,
|
||||||
|
requestSoundPermission: false,
|
||||||
|
notificationCategories: [
|
||||||
|
DarwinNotificationCategory(
|
||||||
|
'single',
|
||||||
|
actions: [
|
||||||
|
DarwinNotificationAction.plain('take_single', 'Take'),
|
||||||
|
DarwinNotificationAction.plain('snooze_single', 'Snooze'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
DarwinNotificationCategory(
|
||||||
|
'group',
|
||||||
|
actions: [
|
||||||
|
DarwinNotificationAction.plain('take_group', 'Take All'),
|
||||||
|
DarwinNotificationAction.plain('snooze_group', 'Snooze'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
const linuxSettings = LinuxInitializationSettings(
|
||||||
|
defaultActionName: 'Open notification',
|
||||||
|
);
|
||||||
|
|
||||||
|
final initSettings = InitializationSettings(
|
||||||
|
android: androidSettings,
|
||||||
|
iOS: iosSettings,
|
||||||
|
linux: linuxSettings,
|
||||||
|
);
|
||||||
|
|
||||||
|
await _plugin.initialize(
|
||||||
|
initSettings,
|
||||||
|
onDidReceiveNotificationResponse: (response) {
|
||||||
|
NotificationRouter.instance.handleNotificationResponse(response);
|
||||||
|
},
|
||||||
|
onDidReceiveBackgroundNotificationResponse: onDidReceiveBackgroundNotificationResponse,
|
||||||
|
);
|
||||||
|
|
||||||
|
_initialized = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Request runtime notification permissions.
|
||||||
|
///
|
||||||
|
/// On Android 13+, this will prompt for POST_NOTIFICATIONS. On older Android,
|
||||||
|
/// this is a no-op. On iOS, it requests alert/badge/sound.
|
||||||
|
Future<bool> requestPermissions() async {
|
||||||
|
// Ensure the plugin is ready before requesting permissions.
|
||||||
|
if (!_initialized) {
|
||||||
|
await initialize();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool granted = true;
|
||||||
|
|
||||||
|
final androidPlugin = _plugin
|
||||||
|
.resolvePlatformSpecificImplementation<
|
||||||
|
AndroidFlutterLocalNotificationsPlugin>();
|
||||||
|
if (androidPlugin != null) {
|
||||||
|
final ok = await androidPlugin.requestNotificationsPermission();
|
||||||
|
granted = granted && (ok == true);
|
||||||
|
}
|
||||||
|
|
||||||
|
final iosPlugin = _plugin
|
||||||
|
.resolvePlatformSpecificImplementation<
|
||||||
|
IOSFlutterLocalNotificationsPlugin>();
|
||||||
|
if (iosPlugin != null) {
|
||||||
|
final ok = await iosPlugin.requestPermissions(
|
||||||
|
alert: true,
|
||||||
|
badge: true,
|
||||||
|
sound: true,
|
||||||
|
);
|
||||||
|
granted = granted && (ok == true);
|
||||||
|
}
|
||||||
|
|
||||||
|
return granted;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Schedule grouped daily reminders for a list of supplements.
|
||||||
|
///
|
||||||
|
/// - Groups supplements by HH:mm and schedules one notification per time slot.
|
||||||
|
/// - Uses daily recurrence via matchDateTimeComponents: DateTimeComponents.time.
|
||||||
|
/// - Keeps iOS pending notifications well below the 64 limit.
|
||||||
|
///
|
||||||
|
/// IDs:
|
||||||
|
/// - Group ID per time slot: 40000 + hour*60 + minute.
|
||||||
|
/// - Stable and predictable for cancel/update operations.
|
||||||
|
Future<void> scheduleDailyGroupedReminders(List<Supplement> supplements) async {
|
||||||
|
if (!_initialized) {
|
||||||
|
await initialize();
|
||||||
|
}
|
||||||
|
|
||||||
|
printLog('🛠 scheduleDailyGroupedReminders -> ${supplements.length} supplements');
|
||||||
|
|
||||||
|
// Clear everything first to avoid duplicates or stale schedules
|
||||||
|
await cancelAll();
|
||||||
|
printLog('🧹 Cleared all existing notifications before scheduling groups');
|
||||||
|
|
||||||
|
// Build groups: HH:mm -> list<Supplement>
|
||||||
|
final Map<String, List<Supplement>> groups = {};
|
||||||
|
for (final s in supplements.where((s) => s.isActive && s.reminderTimes.isNotEmpty && s.id != null)) {
|
||||||
|
for (final timeStr in s.reminderTimes) {
|
||||||
|
final parts = timeStr.split(':');
|
||||||
|
if (parts.length != 2) continue;
|
||||||
|
final hour = int.tryParse(parts[0]);
|
||||||
|
final minute = int.tryParse(parts[1]);
|
||||||
|
if (hour == null || minute == null) continue;
|
||||||
|
|
||||||
|
final key = '${hour.toString().padLeft(2, '0')}:${minute.toString().padLeft(2, '0')}';
|
||||||
|
groups.putIfAbsent(key, () => []).add(s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
printLog('⏱ Found ${groups.length} time group(s): ${groups.keys.toList()}');
|
||||||
|
|
||||||
|
if (groups.isEmpty) {
|
||||||
|
printLog('⚠️ No groups to schedule (no active supplements with reminder times)');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Schedule one notification per time group
|
||||||
|
for (final entry in groups.entries) {
|
||||||
|
final timeKey = entry.key; // HH:mm
|
||||||
|
final items = entry.value;
|
||||||
|
|
||||||
|
final parts = timeKey.split(':');
|
||||||
|
final hour = int.parse(parts[0]);
|
||||||
|
final minute = int.parse(parts[1]);
|
||||||
|
|
||||||
|
final when = _nextInstanceOfTime(hour, minute);
|
||||||
|
final id = 40000 + (hour * 60) + minute;
|
||||||
|
|
||||||
|
final count = items.length;
|
||||||
|
final title = count == 1
|
||||||
|
? 'Time for ${items.first.name}'
|
||||||
|
: 'Time for $count supplements';
|
||||||
|
|
||||||
|
// Build body that lists each supplement concisely
|
||||||
|
final bodyLines = items.map((s) {
|
||||||
|
final units = s.numberOfUnits;
|
||||||
|
final unitType = s.unitType;
|
||||||
|
final perUnit = s.ingredientsPerUnit;
|
||||||
|
return '${s.name} — $units $unitType (${perUnit})';
|
||||||
|
}).toList();
|
||||||
|
final body = bodyLines.join('\n');
|
||||||
|
|
||||||
|
printLog('📅 Scheduling group $timeKey (count=$count) id=$id');
|
||||||
|
printLog('🕒 Now=${tz.TZDateTime.now(tz.local)} | When=$when');
|
||||||
|
|
||||||
|
// Use BigTextStyle/InboxStyle for Android to show multiple lines
|
||||||
|
final bool isSingle = count == 1;
|
||||||
|
// Tag payload with origin meta for debug/inspection
|
||||||
|
final Map<String, dynamic> payloadMap = isSingle
|
||||||
|
? {"type": "single", "id": items.first.id}
|
||||||
|
: {"type": "group", "time": timeKey};
|
||||||
|
payloadMap["meta"] = {"kind": "daily"};
|
||||||
|
final String payloadStr = jsonEncode(payloadMap);
|
||||||
|
|
||||||
|
final androidDetails = AndroidNotificationDetails(
|
||||||
|
_channelDailyId,
|
||||||
|
_channelDailyName,
|
||||||
|
channelDescription: _channelDailyDescription,
|
||||||
|
importance: Importance.high,
|
||||||
|
priority: Priority.high,
|
||||||
|
styleInformation: BigTextStyleInformation(
|
||||||
|
body,
|
||||||
|
contentTitle: title,
|
||||||
|
htmlFormatContentTitle: false,
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
if (isSingle)
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'take_single',
|
||||||
|
'Take',
|
||||||
|
showsUserInterface: true,
|
||||||
|
cancelNotification: true,
|
||||||
|
)
|
||||||
|
else
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'take_group',
|
||||||
|
'Take All',
|
||||||
|
showsUserInterface: true,
|
||||||
|
cancelNotification: true,
|
||||||
|
),
|
||||||
|
if (isSingle)
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'snooze_single',
|
||||||
|
'Snooze',
|
||||||
|
showsUserInterface: false,
|
||||||
|
// Removed cancelNotification: true for debugging
|
||||||
|
)
|
||||||
|
else
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'snooze_group',
|
||||||
|
'Snooze',
|
||||||
|
showsUserInterface: false,
|
||||||
|
// Removed cancelNotification: true for debugging
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
final iosDetails = DarwinNotificationDetails(
|
||||||
|
categoryIdentifier: isSingle ? 'single' : 'group',
|
||||||
|
);
|
||||||
|
|
||||||
|
await _plugin.zonedSchedule(
|
||||||
|
id,
|
||||||
|
title,
|
||||||
|
isSingle ? body : 'Tap to see details',
|
||||||
|
when,
|
||||||
|
NotificationDetails(
|
||||||
|
android: androidDetails,
|
||||||
|
iOS: iosDetails,
|
||||||
|
),
|
||||||
|
androidScheduleMode: AndroidScheduleMode.inexactAllowWhileIdle,
|
||||||
|
matchDateTimeComponents: DateTimeComponents.time,
|
||||||
|
payload: payloadStr,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Log to debug store
|
||||||
|
final createdAtMs = DateTime.now().millisecondsSinceEpoch;
|
||||||
|
await NotificationDebugStore.instance.add(
|
||||||
|
NotificationLogEntry(
|
||||||
|
id: id,
|
||||||
|
kind: 'daily',
|
||||||
|
type: isSingle ? 'single' : 'group',
|
||||||
|
whenEpochMs: when.millisecondsSinceEpoch,
|
||||||
|
createdAtEpochMs: createdAtMs,
|
||||||
|
title: title,
|
||||||
|
payload: payloadStr,
|
||||||
|
singleId: isSingle ? items.first.id as int? : null,
|
||||||
|
timeKey: isSingle ? null : timeKey,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
printLog('✅ Scheduled group $timeKey with ID $id');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Log what the system reports as pending
|
||||||
|
try {
|
||||||
|
final pending = await _plugin.pendingNotificationRequests();
|
||||||
|
printLog('📋 Pending notifications after scheduling: ${pending.length}');
|
||||||
|
for (final p in pending) {
|
||||||
|
printLog(' - ID=${p.id}, Title=${p.title}, BodyLen=${p.body?.length ?? 0}');
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
printLog('⚠️ Could not fetch pending notifications: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convenience to schedule grouped reminders for today and tomorrow.
|
||||||
|
///
|
||||||
|
/// For iOS’s 64 limit, we stick to one day for recurring (matchDateTimeComponents)
|
||||||
|
/// which already repeats every day without needing to schedule future dates.
|
||||||
|
/// If you want an extra safety net, you could schedule tomorrow’s one-offs,
|
||||||
|
/// but with daily components this is unnecessary and risks hitting iOS limits.
|
||||||
|
Future<void> scheduleDailyGroupedRemindersSafe(List<Supplement> supplements) async {
|
||||||
|
// For now, just schedule today’s recurring groups.
|
||||||
|
await scheduleDailyGroupedReminders(supplements);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cancel all scheduled reminders for a given [supplementId].
|
||||||
|
///
|
||||||
|
/// We assume up to 100 slots per supplement (00-99). This is simple and safe.
|
||||||
|
Future<void> cancelSupplementReminders(int supplementId) async {
|
||||||
|
if (!_initialized) {
|
||||||
|
await initialize();
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < 100; i++) {
|
||||||
|
await _plugin.cancel(supplementId * 100 + i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cancel all scheduled notifications.
|
||||||
|
Future<void> cancelAll() async {
|
||||||
|
if (!_initialized) {
|
||||||
|
await initialize();
|
||||||
|
}
|
||||||
|
await _plugin.cancelAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cancel a specific notification by ID.
|
||||||
|
Future<void> cancelById(int id) async {
|
||||||
|
if (!_initialized) {
|
||||||
|
await initialize();
|
||||||
|
}
|
||||||
|
await _plugin.cancel(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Show an immediate notification. Useful for quick diagnostics.
|
||||||
|
Future<void> showInstant({
|
||||||
|
required String title,
|
||||||
|
required String body,
|
||||||
|
String? payload,
|
||||||
|
bool includeSnoozeActions = false, // New parameter
|
||||||
|
bool isSingle = true, // New parameter, defaults to single for instant
|
||||||
|
}) async {
|
||||||
|
if (!_initialized) {
|
||||||
|
await initialize();
|
||||||
|
}
|
||||||
|
|
||||||
|
final androidDetails = AndroidNotificationDetails(
|
||||||
|
'instant_notifications',
|
||||||
|
'Instant Notifications',
|
||||||
|
channelDescription: 'One-off or immediate notifications',
|
||||||
|
importance: Importance.high,
|
||||||
|
priority: Priority.high,
|
||||||
|
actions: includeSnoozeActions
|
||||||
|
? [
|
||||||
|
if (isSingle)
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'take_single',
|
||||||
|
'Take',
|
||||||
|
showsUserInterface: true,
|
||||||
|
cancelNotification: true,
|
||||||
|
)
|
||||||
|
else
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'take_group',
|
||||||
|
'Take All',
|
||||||
|
showsUserInterface: true,
|
||||||
|
cancelNotification: true,
|
||||||
|
),
|
||||||
|
if (isSingle)
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'snooze_single',
|
||||||
|
'Snooze',
|
||||||
|
showsUserInterface: false,
|
||||||
|
cancelNotification: true,
|
||||||
|
)
|
||||||
|
else
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'snooze_group',
|
||||||
|
'Snooze',
|
||||||
|
showsUserInterface: false,
|
||||||
|
cancelNotification: true,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
: [], // No actions by default
|
||||||
|
);
|
||||||
|
|
||||||
|
final iosDetails = DarwinNotificationDetails(
|
||||||
|
categoryIdentifier: includeSnoozeActions
|
||||||
|
? (isSingle ? 'single' : 'group')
|
||||||
|
: null, // Use category for actions
|
||||||
|
);
|
||||||
|
|
||||||
|
await _plugin.show(
|
||||||
|
DateTime.now().millisecondsSinceEpoch ~/ 1000,
|
||||||
|
title,
|
||||||
|
body,
|
||||||
|
NotificationDetails(
|
||||||
|
android: androidDetails,
|
||||||
|
iOS: iosDetails,
|
||||||
|
),
|
||||||
|
payload: payload,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Schedule a one-off (non-repeating) reminder, typically used for Snooze.
|
||||||
|
Future<void> scheduleOneOffReminder({
|
||||||
|
required String title,
|
||||||
|
required String body,
|
||||||
|
required String payload,
|
||||||
|
required bool isSingle,
|
||||||
|
required Duration delay,
|
||||||
|
}) async {
|
||||||
|
if (!_initialized) {
|
||||||
|
await initialize();
|
||||||
|
}
|
||||||
|
|
||||||
|
final when = tz.TZDateTime.now(tz.local).add(delay);
|
||||||
|
final id = DateTime.now().millisecondsSinceEpoch ~/ 1000;
|
||||||
|
|
||||||
|
final androidDetails = AndroidNotificationDetails(
|
||||||
|
_channelDailyId,
|
||||||
|
_channelDailyName,
|
||||||
|
channelDescription: _channelDailyDescription,
|
||||||
|
importance: Importance.high,
|
||||||
|
priority: Priority.high,
|
||||||
|
styleInformation: BigTextStyleInformation(
|
||||||
|
body,
|
||||||
|
contentTitle: title,
|
||||||
|
htmlFormatContentTitle: false,
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
if (isSingle)
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'take_single',
|
||||||
|
'Take',
|
||||||
|
showsUserInterface: true,
|
||||||
|
cancelNotification: true,
|
||||||
|
)
|
||||||
|
else
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'take_group',
|
||||||
|
'Take All',
|
||||||
|
showsUserInterface: true,
|
||||||
|
cancelNotification: true,
|
||||||
|
),
|
||||||
|
if (isSingle)
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'snooze_single',
|
||||||
|
'Snooze',
|
||||||
|
showsUserInterface: false,
|
||||||
|
// Removed cancelNotification: true for debugging
|
||||||
|
)
|
||||||
|
else
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'snooze_group',
|
||||||
|
'Snooze',
|
||||||
|
showsUserInterface: false,
|
||||||
|
// Removed cancelNotification: true for debugging
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
final iosDetails = DarwinNotificationDetails(
|
||||||
|
categoryIdentifier: isSingle ? 'single' : 'group',
|
||||||
|
);
|
||||||
|
|
||||||
|
// Enrich payload with meta for snooze; also capture linkage for logging
|
||||||
|
Map<String, dynamic>? pmap;
|
||||||
|
try {
|
||||||
|
pmap = jsonDecode(payload) as Map<String, dynamic>;
|
||||||
|
} catch (_) {
|
||||||
|
pmap = null;
|
||||||
|
}
|
||||||
|
final createdAtMs = DateTime.now().millisecondsSinceEpoch;
|
||||||
|
String payloadFinal = payload;
|
||||||
|
int? logSingleId;
|
||||||
|
String? logTimeKey;
|
||||||
|
if (pmap != null) {
|
||||||
|
final meta = {
|
||||||
|
'kind': 'snooze',
|
||||||
|
'createdAt': createdAtMs,
|
||||||
|
'delayMin': delay.inMinutes,
|
||||||
|
};
|
||||||
|
pmap['meta'] = meta;
|
||||||
|
if (pmap['type'] == 'single') {
|
||||||
|
final v = pmap['id'];
|
||||||
|
logSingleId = v is int ? v : null;
|
||||||
|
} else if (pmap['type'] == 'group') {
|
||||||
|
logTimeKey = pmap['time'] as String?;
|
||||||
|
}
|
||||||
|
payloadFinal = jsonEncode(pmap);
|
||||||
|
}
|
||||||
|
|
||||||
|
await _plugin.zonedSchedule(
|
||||||
|
id,
|
||||||
|
title,
|
||||||
|
isSingle ? body : 'Tap to see details',
|
||||||
|
when,
|
||||||
|
NotificationDetails(
|
||||||
|
android: androidDetails,
|
||||||
|
iOS: iosDetails,
|
||||||
|
),
|
||||||
|
androidScheduleMode: AndroidScheduleMode.inexactAllowWhileIdle,
|
||||||
|
payload: payloadFinal,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Log to debug store
|
||||||
|
await NotificationDebugStore.instance.add(
|
||||||
|
NotificationLogEntry(
|
||||||
|
id: id,
|
||||||
|
kind: 'snooze',
|
||||||
|
type: isSingle ? 'single' : 'group',
|
||||||
|
whenEpochMs: when.millisecondsSinceEpoch,
|
||||||
|
createdAtEpochMs: createdAtMs,
|
||||||
|
title: title,
|
||||||
|
payload: payloadFinal,
|
||||||
|
singleId: logSingleId,
|
||||||
|
timeKey: logTimeKey,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
printLog('⏰ Scheduled one-off reminder (id=$id) at $when, isSingle=$isSingle');
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<NotificationAppLaunchDetails?> getLaunchDetails() async {
|
||||||
|
if (!_initialized) {
|
||||||
|
await initialize();
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
final details = await _plugin.getNotificationAppLaunchDetails();
|
||||||
|
return details;
|
||||||
|
} catch (e) {
|
||||||
|
printLog('⚠️ getLaunchDetails error: $e');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Helper to compute the next instance of [hour]:[minute] in the local tz.
|
||||||
|
tz.TZDateTime _nextInstanceOfTime(int hour, int minute) {
|
||||||
|
final now = tz.TZDateTime.now(tz.local);
|
||||||
|
var scheduled =
|
||||||
|
tz.TZDateTime(tz.local, now.year, now.month, now.day, hour, minute);
|
||||||
|
|
||||||
|
if (scheduled.isBefore(now)) {
|
||||||
|
scheduled = scheduled.add(const Duration(days: 1));
|
||||||
|
printLog('⏭ Scheduling for tomorrow at ${scheduled.toString()} (${scheduled.timeZoneName})');
|
||||||
|
} else {
|
||||||
|
printLog('⏲ Scheduling for today at ${scheduled.toString()} (${scheduled.timeZoneName})');
|
||||||
|
}
|
||||||
|
return scheduled;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Debug helper to fetch and log all pending notifications.
|
||||||
|
Future<List<PendingNotificationRequest>> getPendingNotifications() async {
|
||||||
|
if (!_initialized) {
|
||||||
|
await initialize();
|
||||||
|
}
|
||||||
|
final list = await _plugin.pendingNotificationRequests();
|
||||||
|
printLog('🧾 getPendingNotifications -> ${list.length} pending');
|
||||||
|
for (final p in list) {
|
||||||
|
printLog(' • ID=${p.id}, Title=${p.title}, Payload=${p.payload}');
|
||||||
|
}
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,928 +0,0 @@
|
|||||||
import 'dart:convert';
|
|
||||||
import 'dart:io';
|
|
||||||
|
|
||||||
import 'package:connectivity_plus/connectivity_plus.dart';
|
|
||||||
import 'package:flutter/foundation.dart';
|
|
||||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
|
||||||
import 'package:webdav_client/webdav_client.dart';
|
|
||||||
|
|
||||||
import '../models/supplement.dart';
|
|
||||||
import '../models/supplement_intake.dart';
|
|
||||||
import '../models/sync_data.dart';
|
|
||||||
import '../models/sync_enums.dart';
|
|
||||||
import 'database_helper.dart';
|
|
||||||
|
|
||||||
/// Service for handling WebDAV synchronization operations
|
|
||||||
class WebDAVSyncService {
|
|
||||||
static const String _baseUrlKey = 'webdav_base_url';
|
|
||||||
static const String _usernameKey = 'webdav_username';
|
|
||||||
static const String _passwordKey = 'webdav_password';
|
|
||||||
static const String _deviceNameKey = 'webdav_device_name';
|
|
||||||
static const String _deviceIdKey = 'webdav_device_id';
|
|
||||||
static const String _lastSyncTimeKey = 'webdav_last_sync_time';
|
|
||||||
static const String _lastWorkingUrlKey = 'webdav_last_working_url';
|
|
||||||
static const String _syncFolderNameKey = 'webdav_sync_folder_name';
|
|
||||||
|
|
||||||
final FlutterSecureStorage _secureStorage = const FlutterSecureStorage(
|
|
||||||
aOptions: AndroidOptions(
|
|
||||||
encryptedSharedPreferences: true,
|
|
||||||
),
|
|
||||||
iOptions: IOSOptions(
|
|
||||||
accessibility: KeychainAccessibility.first_unlock_this_device,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
final DatabaseHelper _databaseHelper = DatabaseHelper.instance;
|
|
||||||
final Connectivity _connectivity = Connectivity();
|
|
||||||
|
|
||||||
Client? _webdavClient;
|
|
||||||
String? _currentDeviceId;
|
|
||||||
String? _currentDeviceName;
|
|
||||||
String? _syncFolderName;
|
|
||||||
|
|
||||||
/// Initialize the service and generate device ID if needed
|
|
||||||
Future<void> initialize() async {
|
|
||||||
await _ensureDeviceInfo();
|
|
||||||
_syncFolderName = await getSyncFolderName();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Check if WebDAV is configured
|
|
||||||
Future<bool> isConfigured() async {
|
|
||||||
final baseUrl = await _secureStorage.read(key: _baseUrlKey);
|
|
||||||
final username = await _secureStorage.read(key: _usernameKey);
|
|
||||||
final password = await _secureStorage.read(key: _passwordKey);
|
|
||||||
|
|
||||||
return baseUrl != null &&
|
|
||||||
baseUrl.isNotEmpty &&
|
|
||||||
username != null &&
|
|
||||||
username.isNotEmpty &&
|
|
||||||
password != null &&
|
|
||||||
password.isNotEmpty;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Configure WebDAV connection
|
|
||||||
Future<bool> configure({
|
|
||||||
required String baseUrl,
|
|
||||||
required String username,
|
|
||||||
String? password,
|
|
||||||
String? deviceName,
|
|
||||||
String? syncFolderName,
|
|
||||||
}) async {
|
|
||||||
try {
|
|
||||||
// For updates without password, get existing password
|
|
||||||
String actualPassword = password ?? '';
|
|
||||||
if (password == null) {
|
|
||||||
actualPassword = await _secureStorage.read(key: _passwordKey) ?? '';
|
|
||||||
if (actualPassword.isEmpty) {
|
|
||||||
throw Exception('No existing password found and no new password provided');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate and normalize base URL
|
|
||||||
final normalizedUrl = _normalizeUrl(baseUrl);
|
|
||||||
|
|
||||||
// Build the full WebDAV URL with username for Nextcloud/ownCloud
|
|
||||||
final fullWebdavUrl = _buildFullWebDAVUrl(normalizedUrl, username);
|
|
||||||
|
|
||||||
// Test connection with smart fallback
|
|
||||||
final testResult = await _testConnectionWithFallback(
|
|
||||||
fullWebdavUrl,
|
|
||||||
username,
|
|
||||||
actualPassword,
|
|
||||||
baseUrl, // Original URL for fallback attempts
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!testResult.success) {
|
|
||||||
throw Exception(testResult.errorMessage);
|
|
||||||
}
|
|
||||||
|
|
||||||
final finalUrl = testResult.workingUrl!;
|
|
||||||
|
|
||||||
// Save configuration with the working URL
|
|
||||||
await _secureStorage.write(key: _baseUrlKey, value: finalUrl);
|
|
||||||
await _secureStorage.write(key: _lastWorkingUrlKey, value: finalUrl);
|
|
||||||
await _secureStorage.write(key: _usernameKey, value: username);
|
|
||||||
await _secureStorage.write(key: _passwordKey, value: actualPassword);
|
|
||||||
|
|
||||||
if (deviceName != null && deviceName.isNotEmpty) {
|
|
||||||
await _secureStorage.write(key: _deviceNameKey, value: deviceName);
|
|
||||||
_currentDeviceName = deviceName;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Store sync folder name
|
|
||||||
final folderName = syncFolderName ?? 'Supplements';
|
|
||||||
await _secureStorage.write(key: _syncFolderNameKey, value: folderName);
|
|
||||||
_syncFolderName = folderName;
|
|
||||||
|
|
||||||
// Initialize client with the working URL
|
|
||||||
_webdavClient = newClient(
|
|
||||||
finalUrl,
|
|
||||||
user: username,
|
|
||||||
password: actualPassword,
|
|
||||||
debug: kDebugMode,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Ensure sync directory exists
|
|
||||||
await _ensureSyncDirectoryExists();
|
|
||||||
|
|
||||||
if (kDebugMode) {
|
|
||||||
print('WebDAV configured successfully: $finalUrl');
|
|
||||||
print('Original URL: $baseUrl -> Detected: $finalUrl');
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
} catch (e) {
|
|
||||||
if (kDebugMode) {
|
|
||||||
print('WebDAV configuration failed: $e');
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Remove WebDAV configuration
|
|
||||||
Future<void> clearConfiguration() async {
|
|
||||||
await _secureStorage.delete(key: _baseUrlKey);
|
|
||||||
await _secureStorage.delete(key: _usernameKey);
|
|
||||||
await _secureStorage.delete(key: _passwordKey);
|
|
||||||
await _secureStorage.delete(key: _deviceNameKey);
|
|
||||||
await _secureStorage.delete(key: _lastSyncTimeKey);
|
|
||||||
await _secureStorage.delete(key: _lastWorkingUrlKey);
|
|
||||||
await _secureStorage.delete(key: _syncFolderNameKey);
|
|
||||||
_webdavClient = null;
|
|
||||||
_syncFolderName = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Test WebDAV connection
|
|
||||||
Future<bool> testConnection() async {
|
|
||||||
try {
|
|
||||||
await _ensureClient();
|
|
||||||
if (_webdavClient == null) return false;
|
|
||||||
|
|
||||||
await _webdavClient!.ping();
|
|
||||||
return true;
|
|
||||||
} catch (e) {
|
|
||||||
if (kDebugMode) {
|
|
||||||
print('WebDAV connection test failed: $e');
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Check if device has internet connectivity
|
|
||||||
Future<bool> hasConnectivity() async {
|
|
||||||
final connectivityResult = await _connectivity.checkConnectivity();
|
|
||||||
return connectivityResult.any((result) =>
|
|
||||||
result == ConnectivityResult.mobile ||
|
|
||||||
result == ConnectivityResult.wifi ||
|
|
||||||
result == ConnectivityResult.ethernet);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Perform full sync operation
|
|
||||||
Future<SyncResult> performSync() async {
|
|
||||||
final syncStartTime = DateTime.now();
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Check connectivity
|
|
||||||
if (!await hasConnectivity()) {
|
|
||||||
return SyncResult.failure(
|
|
||||||
error: 'No internet connection',
|
|
||||||
status: SyncOperationStatus.networkError,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ensure client is initialized
|
|
||||||
await _ensureClient();
|
|
||||||
if (_webdavClient == null) {
|
|
||||||
return SyncResult.failure(
|
|
||||||
error: 'WebDAV client not configured',
|
|
||||||
status: SyncOperationStatus.authenticationError,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Download remote data
|
|
||||||
final remoteSyncData = await _downloadSyncData();
|
|
||||||
|
|
||||||
// Get local data that needs syncing
|
|
||||||
final localSyncData = await _getLocalSyncData();
|
|
||||||
|
|
||||||
// Merge data and detect conflicts
|
|
||||||
final mergeResult = await _mergeData(localSyncData, remoteSyncData);
|
|
||||||
|
|
||||||
// Upload merged data back to server
|
|
||||||
if (mergeResult.hasChanges) {
|
|
||||||
await _uploadSyncData(mergeResult.mergedData);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update local sync status
|
|
||||||
await _updateLocalSyncStatus(mergeResult.mergedData);
|
|
||||||
|
|
||||||
// Update last sync time
|
|
||||||
await _updateLastSyncTime();
|
|
||||||
|
|
||||||
final syncDuration = DateTime.now().difference(syncStartTime);
|
|
||||||
|
|
||||||
return SyncResult.success(
|
|
||||||
conflicts: mergeResult.conflicts,
|
|
||||||
statistics: SyncStatistics(
|
|
||||||
supplementsUploaded: mergeResult.statistics.supplementsUploaded,
|
|
||||||
supplementsDownloaded: mergeResult.statistics.supplementsDownloaded,
|
|
||||||
intakesUploaded: mergeResult.statistics.intakesUploaded,
|
|
||||||
intakesDownloaded: mergeResult.statistics.intakesDownloaded,
|
|
||||||
conflictsResolved: mergeResult.statistics.conflictsResolved,
|
|
||||||
syncDuration: syncDuration,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
} catch (e) {
|
|
||||||
if (kDebugMode) {
|
|
||||||
print('Sync operation failed: $e');
|
|
||||||
}
|
|
||||||
|
|
||||||
SyncOperationStatus status = SyncOperationStatus.serverError;
|
|
||||||
if (e is SocketException || e.toString().contains('network')) {
|
|
||||||
status = SyncOperationStatus.networkError;
|
|
||||||
} else if (e.toString().contains('401') || e.toString().contains('403')) {
|
|
||||||
status = SyncOperationStatus.authenticationError;
|
|
||||||
}
|
|
||||||
|
|
||||||
return SyncResult.failure(
|
|
||||||
error: e.toString(),
|
|
||||||
status: status,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get last sync time
|
|
||||||
Future<DateTime?> getLastSyncTime() async {
|
|
||||||
final lastSyncStr = await _secureStorage.read(key: _lastSyncTimeKey);
|
|
||||||
if (lastSyncStr != null) {
|
|
||||||
return DateTime.tryParse(lastSyncStr);
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get current device info
|
|
||||||
Future<Map<String, String?>> getDeviceInfo() async {
|
|
||||||
await _ensureDeviceInfo();
|
|
||||||
return {
|
|
||||||
'deviceId': _currentDeviceId,
|
|
||||||
'deviceName': _currentDeviceName,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get the last working WebDAV URL
|
|
||||||
Future<String?> getLastWorkingUrl() async {
|
|
||||||
return await _secureStorage.read(key: _lastWorkingUrlKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get stored server URL
|
|
||||||
Future<String?> getServerUrl() async {
|
|
||||||
return await _secureStorage.read(key: _baseUrlKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get stored username
|
|
||||||
Future<String?> getUsername() async {
|
|
||||||
return await _secureStorage.read(key: _usernameKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get stored sync folder name
|
|
||||||
Future<String?> getSyncFolderName() async {
|
|
||||||
final folderName = await _secureStorage.read(key: _syncFolderNameKey);
|
|
||||||
return folderName ?? 'Supplements';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Private methods
|
|
||||||
|
|
||||||
Future<void> _ensureDeviceInfo() async {
|
|
||||||
_currentDeviceId = await _secureStorage.read(key: _deviceIdKey);
|
|
||||||
if (_currentDeviceId == null) {
|
|
||||||
_currentDeviceId = _generateDeviceId();
|
|
||||||
await _secureStorage.write(key: _deviceIdKey, value: _currentDeviceId!);
|
|
||||||
}
|
|
||||||
|
|
||||||
_currentDeviceName = await _secureStorage.read(key: _deviceNameKey);
|
|
||||||
if (_currentDeviceName == null) {
|
|
||||||
_currentDeviceName = _getDefaultDeviceName();
|
|
||||||
await _secureStorage.write(key: _deviceNameKey, value: _currentDeviceName!);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String _generateDeviceId() {
|
|
||||||
final timestamp = DateTime.now().millisecondsSinceEpoch;
|
|
||||||
final random = DateTime.now().microsecond;
|
|
||||||
return 'device_${timestamp}_$random';
|
|
||||||
}
|
|
||||||
|
|
||||||
String _getDefaultDeviceName() {
|
|
||||||
if (Platform.isAndroid) return 'Android Device';
|
|
||||||
if (Platform.isIOS) return 'iOS Device';
|
|
||||||
if (Platform.isWindows) return 'Windows PC';
|
|
||||||
if (Platform.isMacOS) return 'Mac';
|
|
||||||
if (Platform.isLinux) return 'Linux PC';
|
|
||||||
return 'Unknown Device';
|
|
||||||
}
|
|
||||||
|
|
||||||
String _normalizeUrl(String url) {
|
|
||||||
// Clean and trim the URL
|
|
||||||
url = url.trim();
|
|
||||||
if (url.endsWith('/')) {
|
|
||||||
url = url.substring(0, url.length - 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add protocol if missing - try HTTPS first, fallback to HTTP if needed
|
|
||||||
if (!url.startsWith('http://') && !url.startsWith('https://')) {
|
|
||||||
url = 'https://$url';
|
|
||||||
}
|
|
||||||
|
|
||||||
return _detectAndBuildWebDAVUrl(url);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Advanced server detection and WebDAV URL building
|
|
||||||
String _detectAndBuildWebDAVUrl(String baseUrl) {
|
|
||||||
final uri = Uri.tryParse(baseUrl);
|
|
||||||
if (uri == null) return baseUrl;
|
|
||||||
|
|
||||||
final host = uri.host.toLowerCase();
|
|
||||||
final path = uri.path.toLowerCase();
|
|
||||||
|
|
||||||
// If already contains WebDAV path, return as-is
|
|
||||||
if (path.contains('/remote.php/dav') || path.contains('/remote.php/webdav')) {
|
|
||||||
return baseUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Nextcloud detection patterns
|
|
||||||
if (_isNextcloudServer(host, path)) {
|
|
||||||
return _buildNextcloudUrl(baseUrl, uri);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ownCloud detection patterns
|
|
||||||
if (_isOwnCloudServer(host, path)) {
|
|
||||||
return _buildOwnCloudUrl(baseUrl, uri);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generic WebDAV detection
|
|
||||||
if (_isGenericWebDAVServer(host, path)) {
|
|
||||||
return _buildGenericWebDAVUrl(baseUrl, uri);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Default: assume it's a base URL and try Nextcloud first (most common)
|
|
||||||
return _buildNextcloudUrl(baseUrl, uri);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Detect if server is likely Nextcloud
|
|
||||||
bool _isNextcloudServer(String host, String path) {
|
|
||||||
// Common Nextcloud hosting patterns
|
|
||||||
final nextcloudPatterns = [
|
|
||||||
'nextcloud',
|
|
||||||
'cloud',
|
|
||||||
'nc.',
|
|
||||||
'.cloud.',
|
|
||||||
'files.',
|
|
||||||
'drive.',
|
|
||||||
];
|
|
||||||
|
|
||||||
// Check hostname patterns
|
|
||||||
for (final pattern in nextcloudPatterns) {
|
|
||||||
if (host.contains(pattern)) return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check path patterns
|
|
||||||
if (path.contains('nextcloud') || path.contains('index.php/apps/files')) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Detect if server is likely ownCloud
|
|
||||||
bool _isOwnCloudServer(String host, String path) {
|
|
||||||
final owncloudPatterns = [
|
|
||||||
'owncloud',
|
|
||||||
'oc.',
|
|
||||||
'.owncloud.',
|
|
||||||
];
|
|
||||||
|
|
||||||
// Check hostname patterns
|
|
||||||
for (final pattern in owncloudPatterns) {
|
|
||||||
if (host.contains(pattern)) return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check path patterns
|
|
||||||
if (path.contains('owncloud') || path.contains('index.php/apps/files')) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Detect if server might be generic WebDAV
|
|
||||||
bool _isGenericWebDAVServer(String host, String path) {
|
|
||||||
final webdavPatterns = [
|
|
||||||
'webdav',
|
|
||||||
'dav',
|
|
||||||
'caldav',
|
|
||||||
'carddav',
|
|
||||||
];
|
|
||||||
|
|
||||||
// Check hostname and path for WebDAV indicators
|
|
||||||
for (final pattern in webdavPatterns) {
|
|
||||||
if (host.contains(pattern) || path.contains(pattern)) return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Build Nextcloud WebDAV URL with username detection
|
|
||||||
String _buildNextcloudUrl(String baseUrl, Uri uri) {
|
|
||||||
String webdavUrl = '${uri.scheme}://${uri.host}';
|
|
||||||
|
|
||||||
if (uri.hasPort && uri.port != 80 && uri.port != 443) {
|
|
||||||
webdavUrl += ':${uri.port}';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle subdirectory installations
|
|
||||||
String basePath = uri.path;
|
|
||||||
if (basePath.isNotEmpty && basePath != '/') {
|
|
||||||
// Remove common Nextcloud paths that shouldn't be in base
|
|
||||||
basePath = basePath.replaceAll(RegExp(r'/index\.php.*$'), '');
|
|
||||||
basePath = basePath.replaceAll(RegExp(r'/apps/files.*$'), '');
|
|
||||||
webdavUrl += basePath;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add Nextcloud WebDAV path - we'll need username later
|
|
||||||
webdavUrl += '/remote.php/dav/files/';
|
|
||||||
|
|
||||||
return webdavUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Build ownCloud WebDAV URL
|
|
||||||
String _buildOwnCloudUrl(String baseUrl, Uri uri) {
|
|
||||||
String webdavUrl = '${uri.scheme}://${uri.host}';
|
|
||||||
|
|
||||||
if (uri.hasPort && uri.port != 80 && uri.port != 443) {
|
|
||||||
webdavUrl += ':${uri.port}';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle subdirectory installations
|
|
||||||
String basePath = uri.path;
|
|
||||||
if (basePath.isNotEmpty && basePath != '/') {
|
|
||||||
basePath = basePath.replaceAll(RegExp(r'/index\.php.*$'), '');
|
|
||||||
basePath = basePath.replaceAll(RegExp(r'/apps/files.*$'), '');
|
|
||||||
webdavUrl += basePath;
|
|
||||||
}
|
|
||||||
|
|
||||||
webdavUrl += '/remote.php/webdav/';
|
|
||||||
|
|
||||||
return webdavUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Build generic WebDAV URL
|
|
||||||
String _buildGenericWebDAVUrl(String baseUrl, Uri uri) {
|
|
||||||
// For generic WebDAV, we assume the URL provided is correct
|
|
||||||
// but we might need to add common WebDAV paths if missing
|
|
||||||
if (!uri.path.endsWith('/')) {
|
|
||||||
return '$baseUrl/';
|
|
||||||
}
|
|
||||||
return baseUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _ensureClient() async {
|
|
||||||
if (_webdavClient == null) {
|
|
||||||
final baseUrl = await _secureStorage.read(key: _baseUrlKey);
|
|
||||||
final username = await _secureStorage.read(key: _usernameKey);
|
|
||||||
final password = await _secureStorage.read(key: _passwordKey);
|
|
||||||
|
|
||||||
if (baseUrl != null && username != null && password != null) {
|
|
||||||
_webdavClient = newClient(
|
|
||||||
baseUrl,
|
|
||||||
user: username,
|
|
||||||
password: password,
|
|
||||||
debug: kDebugMode,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _ensureSyncDirectoryExists() async {
|
|
||||||
if (_webdavClient == null) return;
|
|
||||||
|
|
||||||
// Get the configured folder name, default to 'Supplements'
|
|
||||||
final folderName = _syncFolderName ?? await getSyncFolderName() ?? 'Supplements';
|
|
||||||
|
|
||||||
try {
|
|
||||||
await _webdavClient!.mkdir(folderName);
|
|
||||||
} catch (e) {
|
|
||||||
// Directory might already exist, ignore error
|
|
||||||
if (kDebugMode && !e.toString().contains('409')) {
|
|
||||||
print('Failed to create sync directory ($folderName): $e');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<SyncData?> _downloadSyncData() async {
|
|
||||||
if (_webdavClient == null) return null;
|
|
||||||
|
|
||||||
try {
|
|
||||||
final folderName = _syncFolderName ?? await getSyncFolderName() ?? 'Supplements';
|
|
||||||
final syncFilePath = '$folderName/${SyncConstants.syncFileName}';
|
|
||||||
final fileData = await _webdavClient!.read(syncFilePath);
|
|
||||||
final jsonString = utf8.decode(fileData);
|
|
||||||
return SyncData.fromJsonString(jsonString);
|
|
||||||
} catch (e) {
|
|
||||||
if (kDebugMode) {
|
|
||||||
print('Failed to download sync data: $e');
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<SyncData> _getLocalSyncData() async {
|
|
||||||
await _ensureDeviceInfo();
|
|
||||||
|
|
||||||
final supplements = await _databaseHelper.getAllSupplements();
|
|
||||||
final archivedSupplements = await _databaseHelper.getArchivedSupplements();
|
|
||||||
final allSupplements = [...supplements, ...archivedSupplements];
|
|
||||||
|
|
||||||
// Get all intakes (we'll need to implement a method to get all intakes)
|
|
||||||
final intakes = await _getAllIntakes();
|
|
||||||
|
|
||||||
return SyncData(
|
|
||||||
version: SyncConstants.currentSyncVersion,
|
|
||||||
deviceId: _currentDeviceId!,
|
|
||||||
deviceName: _currentDeviceName!,
|
|
||||||
syncTimestamp: DateTime.now(),
|
|
||||||
supplements: allSupplements,
|
|
||||||
intakes: intakes,
|
|
||||||
metadata: {
|
|
||||||
'totalSupplements': allSupplements.length,
|
|
||||||
'totalIntakes': intakes.length,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<List<SupplementIntake>> _getAllIntakes() async {
|
|
||||||
// This is a simplified version - in practice, you might want to limit
|
|
||||||
// to a certain date range or implement pagination for large datasets
|
|
||||||
final now = DateTime.now();
|
|
||||||
final oneYearAgo = now.subtract(const Duration(days: 365));
|
|
||||||
|
|
||||||
List<SupplementIntake> allIntakes = [];
|
|
||||||
DateTime current = oneYearAgo;
|
|
||||||
|
|
||||||
while (current.isBefore(now)) {
|
|
||||||
final monthIntakes = await _databaseHelper.getIntakesForMonth(
|
|
||||||
current.year,
|
|
||||||
current.month,
|
|
||||||
);
|
|
||||||
allIntakes.addAll(monthIntakes);
|
|
||||||
current = DateTime(current.year, current.month + 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
return allIntakes;
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<_MergeResult> _mergeData(SyncData local, SyncData? remote) async {
|
|
||||||
if (remote == null) {
|
|
||||||
// No remote data, just mark local data as pending sync
|
|
||||||
return _MergeResult(
|
|
||||||
mergedData: local,
|
|
||||||
conflicts: [],
|
|
||||||
hasChanges: true,
|
|
||||||
statistics: SyncStatistics(
|
|
||||||
supplementsUploaded: local.supplements.length,
|
|
||||||
intakesUploaded: local.intakes.length,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
final conflicts = <SyncConflict>[];
|
|
||||||
final mergedSupplements = <String, Supplement>{};
|
|
||||||
final mergedIntakes = <String, SupplementIntake>{};
|
|
||||||
|
|
||||||
// Merge supplements
|
|
||||||
for (final localSupplement in local.supplements) {
|
|
||||||
mergedSupplements[localSupplement.syncId] = localSupplement;
|
|
||||||
}
|
|
||||||
|
|
||||||
int supplementsDownloaded = 0;
|
|
||||||
int supplementsUploaded = local.supplements.length;
|
|
||||||
|
|
||||||
for (final remoteSupplement in remote.supplements) {
|
|
||||||
final localSupplement = mergedSupplements[remoteSupplement.syncId];
|
|
||||||
|
|
||||||
if (localSupplement == null) {
|
|
||||||
// New remote supplement
|
|
||||||
mergedSupplements[remoteSupplement.syncId] = remoteSupplement;
|
|
||||||
supplementsDownloaded++;
|
|
||||||
} else {
|
|
||||||
// Check for conflicts
|
|
||||||
if (localSupplement.lastModified.isAfter(remoteSupplement.lastModified)) {
|
|
||||||
// Local is newer, keep local
|
|
||||||
continue;
|
|
||||||
} else if (remoteSupplement.lastModified.isAfter(localSupplement.lastModified)) {
|
|
||||||
// Remote is newer, use remote
|
|
||||||
mergedSupplements[remoteSupplement.syncId] = remoteSupplement;
|
|
||||||
supplementsDownloaded++;
|
|
||||||
} else {
|
|
||||||
// Same timestamp - potential conflict if data differs
|
|
||||||
if (!_supplementsEqual(localSupplement, remoteSupplement)) {
|
|
||||||
conflicts.add(SyncConflict(
|
|
||||||
syncId: localSupplement.syncId,
|
|
||||||
type: ConflictType.modification,
|
|
||||||
localTimestamp: localSupplement.lastModified,
|
|
||||||
remoteTimestamp: remoteSupplement.lastModified,
|
|
||||||
localData: localSupplement.toMap(),
|
|
||||||
remoteData: remoteSupplement.toMap(),
|
|
||||||
suggestedResolution: ConflictResolutionStrategy.preferNewer,
|
|
||||||
));
|
|
||||||
|
|
||||||
// For now, keep local version
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Merge intakes (intakes are usually append-only, so fewer conflicts)
|
|
||||||
for (final localIntake in local.intakes) {
|
|
||||||
mergedIntakes[localIntake.syncId] = localIntake;
|
|
||||||
}
|
|
||||||
|
|
||||||
int intakesDownloaded = 0;
|
|
||||||
int intakesUploaded = local.intakes.length;
|
|
||||||
|
|
||||||
for (final remoteIntake in remote.intakes) {
|
|
||||||
if (!mergedIntakes.containsKey(remoteIntake.syncId)) {
|
|
||||||
mergedIntakes[remoteIntake.syncId] = remoteIntake;
|
|
||||||
intakesDownloaded++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
final mergedData = SyncData(
|
|
||||||
version: SyncConstants.currentSyncVersion,
|
|
||||||
deviceId: local.deviceId,
|
|
||||||
deviceName: local.deviceName,
|
|
||||||
syncTimestamp: DateTime.now(),
|
|
||||||
supplements: mergedSupplements.values.toList(),
|
|
||||||
intakes: mergedIntakes.values.toList(),
|
|
||||||
metadata: {
|
|
||||||
'mergedAt': DateTime.now().toIso8601String(),
|
|
||||||
'sourceDevices': [local.deviceId, remote.deviceId],
|
|
||||||
'conflicts': conflicts.length,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
return _MergeResult(
|
|
||||||
mergedData: mergedData,
|
|
||||||
conflicts: conflicts,
|
|
||||||
hasChanges: supplementsDownloaded > 0 || intakesDownloaded > 0 || conflicts.isNotEmpty,
|
|
||||||
statistics: SyncStatistics(
|
|
||||||
supplementsUploaded: supplementsUploaded,
|
|
||||||
supplementsDownloaded: supplementsDownloaded,
|
|
||||||
intakesUploaded: intakesUploaded,
|
|
||||||
intakesDownloaded: intakesDownloaded,
|
|
||||||
conflictsResolved: 0, // Conflicts are not auto-resolved yet
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool _supplementsEqual(Supplement a, Supplement b) {
|
|
||||||
return a.name == b.name &&
|
|
||||||
a.brand == b.brand &&
|
|
||||||
a.numberOfUnits == b.numberOfUnits &&
|
|
||||||
a.unitType == b.unitType &&
|
|
||||||
a.frequencyPerDay == b.frequencyPerDay &&
|
|
||||||
a.reminderTimes.join(',') == b.reminderTimes.join(',') &&
|
|
||||||
a.notes == b.notes &&
|
|
||||||
a.isActive == b.isActive &&
|
|
||||||
a.isDeleted == b.isDeleted &&
|
|
||||||
_ingredientsEqual(a.ingredients, b.ingredients);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool _ingredientsEqual(List ingredients1, List ingredients2) {
|
|
||||||
if (ingredients1.length != ingredients2.length) return false;
|
|
||||||
|
|
||||||
for (int i = 0; i < ingredients1.length; i++) {
|
|
||||||
final ing1 = ingredients1[i];
|
|
||||||
final ing2 = ingredients2[i];
|
|
||||||
if (ing1.name != ing2.name ||
|
|
||||||
ing1.amount != ing2.amount ||
|
|
||||||
ing1.unit != ing2.unit) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _uploadSyncData(SyncData syncData) async {
|
|
||||||
if (_webdavClient == null) return;
|
|
||||||
|
|
||||||
final folderName = _syncFolderName ?? await getSyncFolderName() ?? 'Supplements';
|
|
||||||
final syncFilePath = '$folderName/${SyncConstants.syncFileName}';
|
|
||||||
final jsonString = syncData.toJsonString();
|
|
||||||
final jsonBytes = utf8.encode(jsonString);
|
|
||||||
|
|
||||||
// Create backup of existing file first
|
|
||||||
try {
|
|
||||||
final backupPath = '$folderName/${SyncConstants.syncFileBackupName}';
|
|
||||||
final existingData = await _webdavClient!.read(syncFilePath);
|
|
||||||
await _webdavClient!.write(backupPath, Uint8List.fromList(existingData));
|
|
||||||
} catch (e) {
|
|
||||||
// Backup failed, continue anyway
|
|
||||||
if (kDebugMode) {
|
|
||||||
print('Failed to create backup: $e');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Upload new sync data
|
|
||||||
await _webdavClient!.write(syncFilePath, jsonBytes);
|
|
||||||
|
|
||||||
if (kDebugMode) {
|
|
||||||
print('Sync data uploaded successfully to $folderName');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _updateLocalSyncStatus(SyncData mergedData) async {
|
|
||||||
// Mark all synced items as synced in local database
|
|
||||||
for (final supplement in mergedData.supplements) {
|
|
||||||
if (supplement.syncStatus != SyncStatus.synced) {
|
|
||||||
await _databaseHelper.markSupplementAsSynced(supplement.syncId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (final intake in mergedData.intakes) {
|
|
||||||
if (intake.syncStatus != SyncStatus.synced) {
|
|
||||||
await _databaseHelper.markIntakeAsSynced(intake.syncId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _updateLastSyncTime() async {
|
|
||||||
await _secureStorage.write(
|
|
||||||
key: _lastSyncTimeKey,
|
|
||||||
value: DateTime.now().toIso8601String(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Build full WebDAV URL including username for Nextcloud/ownCloud
|
|
||||||
String _buildFullWebDAVUrl(String baseUrl, String username) {
|
|
||||||
// If URL ends with /files/ (Nextcloud), add username
|
|
||||||
if (baseUrl.endsWith('/remote.php/dav/files/')) {
|
|
||||||
return '$baseUrl$username/';
|
|
||||||
}
|
|
||||||
|
|
||||||
// If URL ends with /webdav/ (ownCloud), it's ready to use
|
|
||||||
if (baseUrl.endsWith('/remote.php/webdav/')) {
|
|
||||||
return baseUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
// For other cases, return as-is
|
|
||||||
return baseUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Test connection with smart fallback logic
|
|
||||||
Future<_ConnectionTestResult> _testConnectionWithFallback(
|
|
||||||
String primaryUrl,
|
|
||||||
String username,
|
|
||||||
String password,
|
|
||||||
String originalUrl,
|
|
||||||
) async {
|
|
||||||
// Try the primary detected URL first
|
|
||||||
try {
|
|
||||||
final client = newClient(primaryUrl, user: username, password: password, debug: kDebugMode);
|
|
||||||
await client.ping();
|
|
||||||
return _ConnectionTestResult.success(primaryUrl);
|
|
||||||
} catch (e) {
|
|
||||||
if (kDebugMode) {
|
|
||||||
print('Primary URL failed: $primaryUrl - $e');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate fallback URLs to try
|
|
||||||
final fallbackUrls = _generateFallbackUrls(originalUrl, username);
|
|
||||||
|
|
||||||
for (final fallbackUrl in fallbackUrls) {
|
|
||||||
try {
|
|
||||||
final client = newClient(fallbackUrl, user: username, password: password, debug: kDebugMode);
|
|
||||||
await client.ping();
|
|
||||||
|
|
||||||
if (kDebugMode) {
|
|
||||||
print('Fallback URL succeeded: $fallbackUrl');
|
|
||||||
}
|
|
||||||
|
|
||||||
return _ConnectionTestResult.success(fallbackUrl);
|
|
||||||
} catch (e) {
|
|
||||||
if (kDebugMode) {
|
|
||||||
print('Fallback URL failed: $fallbackUrl - $e');
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return _ConnectionTestResult.failure('Could not connect to WebDAV server. Please check your server URL, username, and password.');
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Generate fallback URLs to try if primary detection fails
|
|
||||||
List<String> _generateFallbackUrls(String originalUrl, String username) {
|
|
||||||
final fallbackUrls = <String>[];
|
|
||||||
|
|
||||||
final uri = Uri.tryParse(originalUrl.startsWith('http') ? originalUrl : 'https://$originalUrl');
|
|
||||||
if (uri == null) return fallbackUrls;
|
|
||||||
|
|
||||||
String baseUrl = '${uri.scheme}://${uri.host}';
|
|
||||||
if (uri.hasPort && uri.port != 80 && uri.port != 443) {
|
|
||||||
baseUrl += ':${uri.port}';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add path if exists (for subdirectory installations)
|
|
||||||
String installPath = uri.path;
|
|
||||||
if (installPath.isNotEmpty && installPath != '/') {
|
|
||||||
// Clean common paths
|
|
||||||
installPath = installPath.replaceAll(RegExp(r'/index\.php.*$'), '');
|
|
||||||
installPath = installPath.replaceAll(RegExp(r'/apps/files.*$'), '');
|
|
||||||
installPath = installPath.replaceAll(RegExp(r'/remote\.php.*$'), '');
|
|
||||||
baseUrl += installPath;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Try different combinations
|
|
||||||
fallbackUrls.addAll([
|
|
||||||
// Nextcloud variants
|
|
||||||
'$baseUrl/remote.php/dav/files/$username/',
|
|
||||||
'$baseUrl/nextcloud/remote.php/dav/files/$username/',
|
|
||||||
'$baseUrl/cloud/remote.php/dav/files/$username/',
|
|
||||||
|
|
||||||
// ownCloud variants
|
|
||||||
'$baseUrl/remote.php/webdav/',
|
|
||||||
'$baseUrl/owncloud/remote.php/webdav/',
|
|
||||||
|
|
||||||
// Generic WebDAV variants
|
|
||||||
'$baseUrl/webdav/',
|
|
||||||
'$baseUrl/dav/',
|
|
||||||
|
|
||||||
// Try with different protocols if HTTPS failed
|
|
||||||
..._generateProtocolVariants(baseUrl, username),
|
|
||||||
]);
|
|
||||||
|
|
||||||
// Remove duplicates and return
|
|
||||||
return fallbackUrls.toSet().toList();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Generate protocol variants (HTTP/HTTPS)
|
|
||||||
List<String> _generateProtocolVariants(String baseUrl, String username) {
|
|
||||||
if (baseUrl.startsWith('https://')) {
|
|
||||||
// Try HTTP variants
|
|
||||||
final httpBase = baseUrl.replaceFirst('https://', 'http://');
|
|
||||||
return [
|
|
||||||
'$httpBase/remote.php/dav/files/$username/',
|
|
||||||
'$httpBase/remote.php/webdav/',
|
|
||||||
'$httpBase/webdav/',
|
|
||||||
];
|
|
||||||
} else if (baseUrl.startsWith('http://')) {
|
|
||||||
// Try HTTPS variants
|
|
||||||
final httpsBase = baseUrl.replaceFirst('http://', 'https://');
|
|
||||||
return [
|
|
||||||
'$httpsBase/remote.php/dav/files/$username/',
|
|
||||||
'$httpsBase/remote.php/webdav/',
|
|
||||||
'$httpsBase/webdav/',
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Internal class for merge operation results
|
|
||||||
class _MergeResult {
|
|
||||||
final SyncData mergedData;
|
|
||||||
final List<SyncConflict> conflicts;
|
|
||||||
final bool hasChanges;
|
|
||||||
final SyncStatistics statistics;
|
|
||||||
|
|
||||||
const _MergeResult({
|
|
||||||
required this.mergedData,
|
|
||||||
required this.conflicts,
|
|
||||||
required this.hasChanges,
|
|
||||||
required this.statistics,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Internal class for connection test results
|
|
||||||
class _ConnectionTestResult {
|
|
||||||
final bool success;
|
|
||||||
final String? workingUrl;
|
|
||||||
final String? errorMessage;
|
|
||||||
|
|
||||||
const _ConnectionTestResult._({
|
|
||||||
required this.success,
|
|
||||||
this.workingUrl,
|
|
||||||
this.errorMessage,
|
|
||||||
});
|
|
||||||
|
|
||||||
factory _ConnectionTestResult.success(String url) {
|
|
||||||
return _ConnectionTestResult._(success: true, workingUrl: url);
|
|
||||||
}
|
|
||||||
|
|
||||||
factory _ConnectionTestResult.failure(String error) {
|
|
||||||
return _ConnectionTestResult._(success: false, errorMessage: error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
206
lib/widgets/dialogs/bulk_take_dialog.dart
Normal file
206
lib/widgets/dialogs/bulk_take_dialog.dart
Normal file
@@ -0,0 +1,206 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:provider/provider.dart';
|
||||||
|
|
||||||
|
import '../../models/supplement.dart';
|
||||||
|
import '../../providers/supplement_provider.dart';
|
||||||
|
|
||||||
|
/// Shows a bulk "Take supplements" dialog for a list of supplements.
|
||||||
|
/// - No time selection (records as now)
|
||||||
|
/// - Allows editing units per supplement
|
||||||
|
/// - Optional shared notes (applies to all)
|
||||||
|
Future<void> showBulkTakeDialog(
|
||||||
|
BuildContext context,
|
||||||
|
List<Supplement> supplements,
|
||||||
|
) async {
|
||||||
|
if (supplements.isEmpty) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Controllers for each supplement's units
|
||||||
|
final Map<int, TextEditingController> unitControllers = {
|
||||||
|
for (final s in supplements.where((s) => s.id != null))
|
||||||
|
s.id!: TextEditingController(text: s.numberOfUnits.toString()),
|
||||||
|
};
|
||||||
|
|
||||||
|
final notesController = TextEditingController();
|
||||||
|
|
||||||
|
await showDialog(
|
||||||
|
context: context,
|
||||||
|
builder: (context) {
|
||||||
|
return AlertDialog(
|
||||||
|
title: Text('Take ${supplements.length} supplements'),
|
||||||
|
content: SizedBox(
|
||||||
|
width: double.maxFinite,
|
||||||
|
child: ConstrainedBox(
|
||||||
|
constraints: const BoxConstraints(maxWidth: 500),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
// List of supplements with editable units
|
||||||
|
// Use a scroll view with explicit max height to avoid intrinsic dimension issues.
|
||||||
|
ConstrainedBox(
|
||||||
|
constraints: const BoxConstraints(maxHeight: 320),
|
||||||
|
child: SingleChildScrollView(
|
||||||
|
child: Column(
|
||||||
|
children: [
|
||||||
|
for (int index = 0; index < supplements.length; index++) ...[
|
||||||
|
() {
|
||||||
|
final s = supplements[index];
|
||||||
|
final controller = unitControllers[s.id] ??
|
||||||
|
TextEditingController(text: s.numberOfUnits.toString());
|
||||||
|
return Container(
|
||||||
|
padding: const EdgeInsets.all(12),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.5),
|
||||||
|
borderRadius: BorderRadius.circular(8),
|
||||||
|
border: Border.all(
|
||||||
|
color: Theme.of(context).colorScheme.outline.withOpacity(0.3),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
// Name and per-unit info
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
s.name,
|
||||||
|
style: const TextStyle(
|
||||||
|
fontSize: 16,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Text(
|
||||||
|
s.unitType,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
// Units editor
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: TextField(
|
||||||
|
controller: controller,
|
||||||
|
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||||
|
decoration: InputDecoration(
|
||||||
|
labelText: 'Units',
|
||||||
|
border: const OutlineInputBorder(),
|
||||||
|
suffixText: s.unitType,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
// Dosage line
|
||||||
|
Container(
|
||||||
|
width: double.infinity,
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: Theme.of(context).colorScheme.surface,
|
||||||
|
borderRadius: BorderRadius.circular(6),
|
||||||
|
border: Border.all(
|
||||||
|
color: Theme.of(context).colorScheme.outline.withOpacity(0.3),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
'Per unit:',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Text(
|
||||||
|
s.ingredientsDisplay,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: Theme.of(context).colorScheme.onSurface,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}(),
|
||||||
|
if (index != supplements.length - 1) const SizedBox(height: 8),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
// Shared notes
|
||||||
|
TextField(
|
||||||
|
controller: notesController,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: 'Notes for all (optional)',
|
||||||
|
border: OutlineInputBorder(),
|
||||||
|
),
|
||||||
|
maxLines: 2,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
)),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.of(context).pop(),
|
||||||
|
child: const Text('Cancel'),
|
||||||
|
),
|
||||||
|
ElevatedButton(
|
||||||
|
onPressed: () {
|
||||||
|
final provider = context.read<SupplementProvider>();
|
||||||
|
int recorded = 0;
|
||||||
|
|
||||||
|
for (final s in supplements) {
|
||||||
|
if (s.id == null) continue;
|
||||||
|
final controller = unitControllers[s.id]!;
|
||||||
|
final units = double.tryParse(controller.text) ?? s.numberOfUnits.toDouble();
|
||||||
|
|
||||||
|
// totalDosageTaken stays 0.0 for now (ingredients-based tracking later)
|
||||||
|
provider.recordIntake(
|
||||||
|
s.id!,
|
||||||
|
0.0,
|
||||||
|
unitsTaken: units,
|
||||||
|
notes: notesController.text.isNotEmpty ? notesController.text : null,
|
||||||
|
takenAt: null, // "now"
|
||||||
|
);
|
||||||
|
recorded++;
|
||||||
|
}
|
||||||
|
|
||||||
|
Navigator.of(context).pop();
|
||||||
|
if (recorded > 0) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text('Recorded $recorded supplement${recorded == 1 ? '' : 's'}'),
|
||||||
|
backgroundColor: Colors.green,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
child: const Text('Record All'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Dispose controllers
|
||||||
|
for (final c in unitControllers.values) {
|
||||||
|
c.dispose();
|
||||||
|
}
|
||||||
|
notesController.dispose();
|
||||||
|
}
|
||||||
277
lib/widgets/dialogs/take_supplement_dialog.dart
Normal file
277
lib/widgets/dialogs/take_supplement_dialog.dart
Normal file
@@ -0,0 +1,277 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:provider/provider.dart';
|
||||||
|
|
||||||
|
import '../../models/supplement.dart';
|
||||||
|
import '../../providers/supplement_provider.dart';
|
||||||
|
|
||||||
|
/// Shows the "Take supplement" dialog.
|
||||||
|
/// - If [hideTime] is true, the time selection UI is hidden and intake is recorded as "now".
|
||||||
|
Future<void> showTakeSupplementDialog(
|
||||||
|
BuildContext context,
|
||||||
|
Supplement supplement, {
|
||||||
|
bool hideTime = false,
|
||||||
|
}) async {
|
||||||
|
final unitsController = TextEditingController(text: supplement.numberOfUnits.toString());
|
||||||
|
final notesController = TextEditingController();
|
||||||
|
DateTime selectedDateTime = DateTime.now();
|
||||||
|
bool useCustomTime = false;
|
||||||
|
|
||||||
|
await showDialog(
|
||||||
|
context: context,
|
||||||
|
builder: (context) => StatefulBuilder(
|
||||||
|
builder: (context, setState) {
|
||||||
|
return AlertDialog(
|
||||||
|
title: Text('Take ${supplement.name}'),
|
||||||
|
content: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: TextField(
|
||||||
|
controller: unitsController,
|
||||||
|
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||||
|
decoration: InputDecoration(
|
||||||
|
labelText: 'Number of ${supplement.unitType}',
|
||||||
|
border: const OutlineInputBorder(),
|
||||||
|
suffixText: supplement.unitType,
|
||||||
|
),
|
||||||
|
onChanged: (value) => setState(() {}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Container(
|
||||||
|
padding: const EdgeInsets.all(8),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: Theme.of(context).colorScheme.surfaceVariant,
|
||||||
|
borderRadius: BorderRadius.circular(4),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
'Total dosage:',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Text(
|
||||||
|
supplement.ingredientsDisplay,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: Theme.of(context).colorScheme.onSurface,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
|
||||||
|
if (!hideTime) ...[
|
||||||
|
// Time selection section
|
||||||
|
Container(
|
||||||
|
padding: const EdgeInsets.all(12),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: Theme.of(context).colorScheme.primaryContainer.withOpacity(0.3),
|
||||||
|
borderRadius: BorderRadius.circular(8),
|
||||||
|
border: Border.all(
|
||||||
|
color: Theme.of(context).colorScheme.primary.withOpacity(0.3),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.access_time,
|
||||||
|
size: 16,
|
||||||
|
color: Theme.of(context).colorScheme.primary,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 6),
|
||||||
|
Text(
|
||||||
|
'When did you take it?',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: Theme.of(context).colorScheme.primary,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: RadioListTile<bool>(
|
||||||
|
dense: true,
|
||||||
|
contentPadding: EdgeInsets.zero,
|
||||||
|
title: const Text('Just now', style: TextStyle(fontSize: 12)),
|
||||||
|
value: false,
|
||||||
|
groupValue: useCustomTime,
|
||||||
|
onChanged: (value) => setState(() => useCustomTime = value!),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Expanded(
|
||||||
|
child: RadioListTile<bool>(
|
||||||
|
dense: true,
|
||||||
|
contentPadding: EdgeInsets.zero,
|
||||||
|
title: const Text('Custom time', style: TextStyle(fontSize: 12)),
|
||||||
|
value: true,
|
||||||
|
groupValue: useCustomTime,
|
||||||
|
onChanged: (value) => setState(() => useCustomTime = value!),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
if (useCustomTime) ...[
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Container(
|
||||||
|
width: double.infinity,
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: Theme.of(context).colorScheme.surface,
|
||||||
|
borderRadius: BorderRadius.circular(6),
|
||||||
|
border: Border.all(
|
||||||
|
color: Theme.of(context).colorScheme.outline.withOpacity(0.5),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
children: [
|
||||||
|
// Date picker
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.calendar_today,
|
||||||
|
size: 14,
|
||||||
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
'Date: ${selectedDateTime.day}/${selectedDateTime.month}/${selectedDateTime.year}',
|
||||||
|
style: const TextStyle(fontSize: 12),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
TextButton(
|
||||||
|
onPressed: () async {
|
||||||
|
final date = await showDatePicker(
|
||||||
|
context: context,
|
||||||
|
initialDate: selectedDateTime,
|
||||||
|
firstDate: DateTime.now().subtract(const Duration(days: 7)),
|
||||||
|
lastDate: DateTime.now(),
|
||||||
|
);
|
||||||
|
if (date != null) {
|
||||||
|
setState(() {
|
||||||
|
selectedDateTime = DateTime(
|
||||||
|
date.year,
|
||||||
|
date.month,
|
||||||
|
date.day,
|
||||||
|
selectedDateTime.hour,
|
||||||
|
selectedDateTime.minute,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
child: const Text('Change', style: TextStyle(fontSize: 10)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
// Time picker
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.access_time,
|
||||||
|
size: 14,
|
||||||
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
'Time: ${selectedDateTime.hour.toString().padLeft(2, '0')}:${selectedDateTime.minute.toString().padLeft(2, '0')}',
|
||||||
|
style: const TextStyle(fontSize: 12),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
TextButton(
|
||||||
|
onPressed: () async {
|
||||||
|
final time = await showTimePicker(
|
||||||
|
context: context,
|
||||||
|
initialTime: TimeOfDay.fromDateTime(selectedDateTime),
|
||||||
|
);
|
||||||
|
if (time != null) {
|
||||||
|
setState(() {
|
||||||
|
selectedDateTime = DateTime(
|
||||||
|
selectedDateTime.year,
|
||||||
|
selectedDateTime.month,
|
||||||
|
selectedDateTime.day,
|
||||||
|
time.hour,
|
||||||
|
time.minute,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
child: const Text('Change', style: TextStyle(fontSize: 10)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
],
|
||||||
|
|
||||||
|
TextField(
|
||||||
|
controller: notesController,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: 'Notes (optional)',
|
||||||
|
border: OutlineInputBorder(),
|
||||||
|
),
|
||||||
|
maxLines: 2,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.of(context).pop(),
|
||||||
|
child: const Text('Cancel'),
|
||||||
|
),
|
||||||
|
ElevatedButton(
|
||||||
|
onPressed: () {
|
||||||
|
final unitsTaken = double.tryParse(unitsController.text) ?? supplement.numberOfUnits.toDouble();
|
||||||
|
// For now, we'll record 0 as total dosage since we're transitioning to ingredients
|
||||||
|
// This will be properly implemented when we add the full ingredient tracking
|
||||||
|
final totalDosageTaken = 0.0;
|
||||||
|
context.read<SupplementProvider>().recordIntake(
|
||||||
|
supplement.id!,
|
||||||
|
totalDosageTaken,
|
||||||
|
unitsTaken: unitsTaken,
|
||||||
|
notes: notesController.text.isNotEmpty ? notesController.text : null,
|
||||||
|
takenAt: hideTime
|
||||||
|
? null
|
||||||
|
: (useCustomTime ? selectedDateTime : null),
|
||||||
|
);
|
||||||
|
Navigator.of(context).pop();
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text('${supplement.name} recorded!'),
|
||||||
|
backgroundColor: Colors.green,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
child: const Text('Record'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
49
lib/widgets/info_chip.dart
Normal file
49
lib/widgets/info_chip.dart
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
class InfoChip extends StatelessWidget {
|
||||||
|
final IconData icon;
|
||||||
|
final String label;
|
||||||
|
final BuildContext context;
|
||||||
|
final bool fullWidth;
|
||||||
|
|
||||||
|
const InfoChip({
|
||||||
|
required this.icon,
|
||||||
|
required this.label,
|
||||||
|
required this.context,
|
||||||
|
this.fullWidth = false,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Container(
|
||||||
|
width: fullWidth ? double.infinity : null,
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.4),
|
||||||
|
borderRadius: BorderRadius.circular(8),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: fullWidth ? MainAxisSize.max : MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
icon,
|
||||||
|
size: 14,
|
||||||
|
color: Theme.of(context).colorScheme.outline,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
Flexible(
|
||||||
|
child: Text(
|
||||||
|
label,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11,
|
||||||
|
color: Theme.of(context).colorScheme.outline,
|
||||||
|
fontWeight: FontWeight.w500,
|
||||||
|
),
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@ class SupplementCard extends StatefulWidget {
|
|||||||
final VoidCallback onEdit;
|
final VoidCallback onEdit;
|
||||||
final VoidCallback onDelete;
|
final VoidCallback onDelete;
|
||||||
final VoidCallback onArchive;
|
final VoidCallback onArchive;
|
||||||
|
final VoidCallback onDuplicate;
|
||||||
|
|
||||||
const SupplementCard({
|
const SupplementCard({
|
||||||
super.key,
|
super.key,
|
||||||
@@ -17,6 +18,7 @@ class SupplementCard extends StatefulWidget {
|
|||||||
required this.onEdit,
|
required this.onEdit,
|
||||||
required this.onDelete,
|
required this.onDelete,
|
||||||
required this.onArchive,
|
required this.onArchive,
|
||||||
|
required this.onDuplicate,
|
||||||
});
|
});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -42,7 +44,7 @@ class _SupplementCardState extends State<SupplementCard> {
|
|||||||
final unitsTaken = intake['unitsTaken'] ?? 1.0;
|
final unitsTaken = intake['unitsTaken'] ?? 1.0;
|
||||||
return {
|
return {
|
||||||
'time': '${takenAt.hour.toString().padLeft(2, '0')}:${takenAt.minute.toString().padLeft(2, '0')}',
|
'time': '${takenAt.hour.toString().padLeft(2, '0')}:${takenAt.minute.toString().padLeft(2, '0')}',
|
||||||
'units': unitsTaken,
|
'units': unitsTaken is int ? unitsTaken.toDouble() : unitsTaken as double,
|
||||||
};
|
};
|
||||||
}).toList();
|
}).toList();
|
||||||
|
|
||||||
@@ -175,7 +177,7 @@ class _SupplementCardState extends State<SupplementCard> {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
ElevatedButton(
|
ElevatedButton(
|
||||||
onPressed: isCompletelyTaken ? null : widget.onTake,
|
onPressed: widget.onTake,
|
||||||
style: ElevatedButton.styleFrom(
|
style: ElevatedButton.styleFrom(
|
||||||
backgroundColor: isCompletelyTaken
|
backgroundColor: isCompletelyTaken
|
||||||
? Colors.green.shade500
|
? Colors.green.shade500
|
||||||
@@ -209,6 +211,9 @@ class _SupplementCardState extends State<SupplementCard> {
|
|||||||
case 'edit':
|
case 'edit':
|
||||||
widget.onEdit();
|
widget.onEdit();
|
||||||
break;
|
break;
|
||||||
|
case 'duplicate':
|
||||||
|
widget.onDuplicate();
|
||||||
|
break;
|
||||||
case 'archive':
|
case 'archive':
|
||||||
widget.onArchive();
|
widget.onArchive();
|
||||||
break;
|
break;
|
||||||
@@ -218,6 +223,18 @@ class _SupplementCardState extends State<SupplementCard> {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
itemBuilder: (context) => [
|
itemBuilder: (context) => [
|
||||||
|
if (isTakenToday)
|
||||||
|
PopupMenuItem(
|
||||||
|
value: 'take',
|
||||||
|
onTap: widget.onTake,
|
||||||
|
child: const Row(
|
||||||
|
children: [
|
||||||
|
Icon(Icons.add_circle_outline),
|
||||||
|
SizedBox(width: 8),
|
||||||
|
Text('Take Again'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
const PopupMenuItem(
|
const PopupMenuItem(
|
||||||
value: 'edit',
|
value: 'edit',
|
||||||
child: Row(
|
child: Row(
|
||||||
@@ -228,6 +245,16 @@ class _SupplementCardState extends State<SupplementCard> {
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
const PopupMenuItem(
|
||||||
|
value: 'duplicate',
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Icon(Icons.copy),
|
||||||
|
SizedBox(width: 8),
|
||||||
|
Text('Duplicate'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
const PopupMenuItem(
|
const PopupMenuItem(
|
||||||
value: 'archive',
|
value: 'archive',
|
||||||
child: Row(
|
child: Row(
|
||||||
@@ -434,7 +461,7 @@ class _SupplementCardState extends State<SupplementCard> {
|
|||||||
SizedBox(
|
SizedBox(
|
||||||
width: double.infinity,
|
width: double.infinity,
|
||||||
child: ElevatedButton.icon(
|
child: ElevatedButton.icon(
|
||||||
onPressed: isCompletelyTaken ? null : widget.onTake,
|
onPressed: widget.onTake,
|
||||||
icon: Icon(
|
icon: Icon(
|
||||||
isCompletelyTaken ? Icons.check_circle : Icons.medication,
|
isCompletelyTaken ? Icons.check_circle : Icons.medication,
|
||||||
size: 18,
|
size: 18,
|
||||||
|
|||||||
@@ -7,9 +7,13 @@
|
|||||||
#include "generated_plugin_registrant.h"
|
#include "generated_plugin_registrant.h"
|
||||||
|
|
||||||
#include <flutter_secure_storage_linux/flutter_secure_storage_linux_plugin.h>
|
#include <flutter_secure_storage_linux/flutter_secure_storage_linux_plugin.h>
|
||||||
|
#include <url_launcher_linux/url_launcher_plugin.h>
|
||||||
|
|
||||||
void fl_register_plugins(FlPluginRegistry* registry) {
|
void fl_register_plugins(FlPluginRegistry* registry) {
|
||||||
g_autoptr(FlPluginRegistrar) flutter_secure_storage_linux_registrar =
|
g_autoptr(FlPluginRegistrar) flutter_secure_storage_linux_registrar =
|
||||||
fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStorageLinuxPlugin");
|
fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStorageLinuxPlugin");
|
||||||
flutter_secure_storage_linux_plugin_register_with_registrar(flutter_secure_storage_linux_registrar);
|
flutter_secure_storage_linux_plugin_register_with_registrar(flutter_secure_storage_linux_registrar);
|
||||||
|
g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar =
|
||||||
|
fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin");
|
||||||
|
url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
list(APPEND FLUTTER_PLUGIN_LIST
|
list(APPEND FLUTTER_PLUGIN_LIST
|
||||||
flutter_secure_storage_linux
|
flutter_secure_storage_linux
|
||||||
|
url_launcher_linux
|
||||||
)
|
)
|
||||||
|
|
||||||
list(APPEND FLUTTER_FFI_PLUGIN_LIST
|
list(APPEND FLUTTER_FFI_PLUGIN_LIST
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import flutter_secure_storage_darwin
|
|||||||
import path_provider_foundation
|
import path_provider_foundation
|
||||||
import shared_preferences_foundation
|
import shared_preferences_foundation
|
||||||
import sqflite_darwin
|
import sqflite_darwin
|
||||||
|
import url_launcher_macos
|
||||||
|
|
||||||
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
|
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
|
||||||
ConnectivityPlusPlugin.register(with: registry.registrar(forPlugin: "ConnectivityPlusPlugin"))
|
ConnectivityPlusPlugin.register(with: registry.registrar(forPlugin: "ConnectivityPlusPlugin"))
|
||||||
@@ -19,4 +20,5 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
|
|||||||
PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin"))
|
PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin"))
|
||||||
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
|
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
|
||||||
SqflitePlugin.register(with: registry.registrar(forPlugin: "SqflitePlugin"))
|
SqflitePlugin.register(with: registry.registrar(forPlugin: "SqflitePlugin"))
|
||||||
|
UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin"))
|
||||||
}
|
}
|
||||||
|
|||||||
112
pubspec.lock
112
pubspec.lock
@@ -1,6 +1,14 @@
|
|||||||
# Generated by pub
|
# Generated by pub
|
||||||
# See https://dart.dev/tools/pub/glossary#lockfile
|
# See https://dart.dev/tools/pub/glossary#lockfile
|
||||||
packages:
|
packages:
|
||||||
|
alarm:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
name: alarm
|
||||||
|
sha256: "1eef91f0b803a2370137e0dada9c7c24cc31edf4f1c30b06442dcf486cc192e0"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "5.1.4"
|
||||||
args:
|
args:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -113,6 +121,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "2.1.1"
|
version: "2.1.1"
|
||||||
|
equatable:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: equatable
|
||||||
|
sha256: "567c64b3cb4cf82397aac55f4f0cbd3ca20d77c6c03bedbc4ceaddc08904aef7"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.0.7"
|
||||||
fake_async:
|
fake_async:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -150,6 +166,14 @@ packages:
|
|||||||
description: flutter
|
description: flutter
|
||||||
source: sdk
|
source: sdk
|
||||||
version: "0.0.0"
|
version: "0.0.0"
|
||||||
|
flutter_fgbg:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: flutter_fgbg
|
||||||
|
sha256: eb6da9b2047372566a6e17b505975fe5bace94af01f6fc825c4b6f81baa6c447
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.7.1"
|
||||||
flutter_lints:
|
flutter_lints:
|
||||||
dependency: "direct dev"
|
dependency: "direct dev"
|
||||||
description:
|
description:
|
||||||
@@ -273,6 +297,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "0.20.2"
|
version: "0.20.2"
|
||||||
|
json_annotation:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: json_annotation
|
||||||
|
sha256: "1ce844379ca14835a50d2f019a3099f419082cfdd231cd86a142af94dd5c6bb1"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "4.9.0"
|
||||||
leak_tracker:
|
leak_tracker:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -305,6 +337,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "6.0.0"
|
version: "6.0.0"
|
||||||
|
logging:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: logging
|
||||||
|
sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.3.0"
|
||||||
matcher:
|
matcher:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -441,6 +481,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "6.1.5+1"
|
version: "6.1.5+1"
|
||||||
|
rxdart:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: rxdart
|
||||||
|
sha256: "5c3004a4a8dbb94bd4bf5412a4def4acdaa12e12f269737a5751369e12d1a962"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.28.0"
|
||||||
shared_preferences:
|
shared_preferences:
|
||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
@@ -638,6 +686,70 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.4.0"
|
version: "1.4.0"
|
||||||
|
url_launcher:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
name: url_launcher
|
||||||
|
sha256: f6a7e5c4835bb4e3026a04793a4199ca2d14c739ec378fdfe23fc8075d0439f8
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "6.3.2"
|
||||||
|
url_launcher_android:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: url_launcher_android
|
||||||
|
sha256: "69ee86740f2847b9a4ba6cffa74ed12ce500bbe2b07f3dc1e643439da60637b7"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "6.3.18"
|
||||||
|
url_launcher_ios:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: url_launcher_ios
|
||||||
|
sha256: d80b3f567a617cb923546034cc94bfe44eb15f989fe670b37f26abdb9d939cb7
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "6.3.4"
|
||||||
|
url_launcher_linux:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: url_launcher_linux
|
||||||
|
sha256: "4e9ba368772369e3e08f231d2301b4ef72b9ff87c31192ef471b380ef29a4935"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "3.2.1"
|
||||||
|
url_launcher_macos:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: url_launcher_macos
|
||||||
|
sha256: c043a77d6600ac9c38300567f33ef12b0ef4f4783a2c1f00231d2b1941fea13f
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "3.2.3"
|
||||||
|
url_launcher_platform_interface:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: url_launcher_platform_interface
|
||||||
|
sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.3.2"
|
||||||
|
url_launcher_web:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: url_launcher_web
|
||||||
|
sha256: "4bd2b7b4dc4d4d0b94e5babfffbca8eac1a126c7f3d6ecbc1a11013faa3abba2"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.4.1"
|
||||||
|
url_launcher_windows:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: url_launcher_windows
|
||||||
|
sha256: "3284b6d2ac454cf34f114e1d3319866fdd1e19cdc329999057e44ffe936cfa77"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "3.1.4"
|
||||||
uuid:
|
uuid:
|
||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
name: supplements
|
name: supplements
|
||||||
description: "A supplement tracking app for managing your daily supplements"
|
description: "A supplement tracking app for managing your daily supplements"
|
||||||
publish_to: "none"
|
publish_to: "none"
|
||||||
version: 1.0.2+27082025
|
version: 1.0.8+30082025
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.9.0
|
sdk: ^3.9.0
|
||||||
@@ -35,6 +35,8 @@ dependencies:
|
|||||||
flutter_secure_storage: ^10.0.0-beta.4
|
flutter_secure_storage: ^10.0.0-beta.4
|
||||||
uuid: ^4.5.1
|
uuid: ^4.5.1
|
||||||
crypto: ^3.0.6
|
crypto: ^3.0.6
|
||||||
|
url_launcher: ^6.3.2
|
||||||
|
alarm: ^5.1.4
|
||||||
|
|
||||||
dev_dependencies:
|
dev_dependencies:
|
||||||
flutter_test:
|
flutter_test:
|
||||||
|
|||||||
@@ -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);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -8,10 +8,13 @@
|
|||||||
|
|
||||||
#include <connectivity_plus/connectivity_plus_windows_plugin.h>
|
#include <connectivity_plus/connectivity_plus_windows_plugin.h>
|
||||||
#include <flutter_secure_storage_windows/flutter_secure_storage_windows_plugin.h>
|
#include <flutter_secure_storage_windows/flutter_secure_storage_windows_plugin.h>
|
||||||
|
#include <url_launcher_windows/url_launcher_windows.h>
|
||||||
|
|
||||||
void RegisterPlugins(flutter::PluginRegistry* registry) {
|
void RegisterPlugins(flutter::PluginRegistry* registry) {
|
||||||
ConnectivityPlusWindowsPluginRegisterWithRegistrar(
|
ConnectivityPlusWindowsPluginRegisterWithRegistrar(
|
||||||
registry->GetRegistrarForPlugin("ConnectivityPlusWindowsPlugin"));
|
registry->GetRegistrarForPlugin("ConnectivityPlusWindowsPlugin"));
|
||||||
FlutterSecureStorageWindowsPluginRegisterWithRegistrar(
|
FlutterSecureStorageWindowsPluginRegisterWithRegistrar(
|
||||||
registry->GetRegistrarForPlugin("FlutterSecureStorageWindowsPlugin"));
|
registry->GetRegistrarForPlugin("FlutterSecureStorageWindowsPlugin"));
|
||||||
|
UrlLauncherWindowsRegisterWithRegistrar(
|
||||||
|
registry->GetRegistrarForPlugin("UrlLauncherWindows"));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
list(APPEND FLUTTER_PLUGIN_LIST
|
list(APPEND FLUTTER_PLUGIN_LIST
|
||||||
connectivity_plus
|
connectivity_plus
|
||||||
flutter_secure_storage_windows
|
flutter_secure_storage_windows
|
||||||
|
url_launcher_windows
|
||||||
)
|
)
|
||||||
|
|
||||||
list(APPEND FLUTTER_FFI_PLUGIN_LIST
|
list(APPEND FLUTTER_FFI_PLUGIN_LIST
|
||||||
|
|||||||
Reference in New Issue
Block a user