571 lines
22 KiB
Dart
571 lines
22 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:intl/intl.dart';
|
|
import 'package:provider/provider.dart';
|
|
|
|
import '../services/app_state.dart';
|
|
import '../services/cloud/cloud_storage_provider.dart';
|
|
import '../services/onboarding_keys.dart';
|
|
import 'cloud_folder_browser_screen.dart';
|
|
|
|
/// "Data" settings submenu, reached from [SettingsScreen]: cloud storage
|
|
/// connection, the two photo-handling switches, and an Advanced section
|
|
/// (stale sync lock timeout, plus the destructive purge actions — grouped
|
|
/// there rather than given their own top-level "Danger Zone" so they sit
|
|
/// behind the same disclosure as other rarely-touched settings).
|
|
class DataSettingsScreen extends StatefulWidget {
|
|
const DataSettingsScreen({super.key});
|
|
|
|
@override
|
|
State<DataSettingsScreen> createState() => _DataSettingsScreenState();
|
|
}
|
|
|
|
class _DataSettingsScreenState extends State<DataSettingsScreen> {
|
|
static final _dateFormat = DateFormat.yMMMd();
|
|
|
|
bool _busy = false;
|
|
String? _error;
|
|
|
|
DateTime? _purgeRangeStart;
|
|
DateTime? _purgeRangeEnd;
|
|
String? _purgeRangeError;
|
|
|
|
Future<void> _connect(CloudProviderId id) async {
|
|
setState(() {
|
|
_busy = true;
|
|
_error = null;
|
|
});
|
|
try {
|
|
await context.read<AppState>().connectProvider(id);
|
|
} catch (e) {
|
|
setState(() => _error = 'Could not sign in: $e');
|
|
} finally {
|
|
if (mounted) setState(() => _busy = false);
|
|
}
|
|
}
|
|
|
|
Future<void> _connectManual(CloudProviderId id, String providerName) async {
|
|
final credentials = await showDialog<_WebDavCredentials>(
|
|
context: context,
|
|
builder: (_) => _WebDavCredentialsDialog(providerName: providerName),
|
|
);
|
|
if (credentials == null || !mounted) return;
|
|
|
|
setState(() {
|
|
_busy = true;
|
|
_error = null;
|
|
});
|
|
try {
|
|
await context.read<AppState>().connectProviderWithCredentials(
|
|
id,
|
|
serverUrl: credentials.serverUrl,
|
|
username: credentials.username,
|
|
password: credentials.password,
|
|
);
|
|
} catch (e) {
|
|
setState(() => _error = 'Could not connect: $e');
|
|
} finally {
|
|
if (mounted) setState(() => _busy = false);
|
|
}
|
|
}
|
|
|
|
Future<void> _disconnect() async {
|
|
setState(() => _busy = true);
|
|
try {
|
|
await context.read<AppState>().disconnectCloud();
|
|
} finally {
|
|
if (mounted) setState(() => _busy = false);
|
|
}
|
|
}
|
|
|
|
void _chooseFolder() {
|
|
Navigator.of(context).push(
|
|
MaterialPageRoute(builder: (_) => const CloudFolderBrowserScreen()),
|
|
);
|
|
}
|
|
|
|
Future<void> _syncNow() async {
|
|
setState(() => _busy = true);
|
|
try {
|
|
await context.read<AppState>().syncNow();
|
|
} finally {
|
|
if (mounted) setState(() => _busy = false);
|
|
}
|
|
}
|
|
|
|
/// The resting (non-syncing) Sync Now icon — badged with the same
|
|
/// play-triangle [CloudBackupActionButton] uses, for anyone who isn't on
|
|
/// an active ad-free purchase, since tapping this can trigger the
|
|
/// rewarded ad gate (see [AppState.syncNow]/`AdService.showGateAd`). Not
|
|
/// a live prediction of whether *this* tap specifically will show one —
|
|
/// same general "this leads to an ad-supported feature" disclosure the
|
|
/// icon-badge uses elsewhere, not an attempt to account for the open
|
|
/// gate window or the free-first-sync case.
|
|
Widget _syncNowIcon(BuildContext context, AppState appState) {
|
|
const icon = Icon(Icons.sync);
|
|
if (appState.adsCurrentlyDisabled) return icon;
|
|
final colors = Theme.of(context).colorScheme;
|
|
return Badge(
|
|
backgroundColor: colors.tertiary,
|
|
label: Icon(Icons.play_arrow, size: 8, color: colors.onTertiary),
|
|
child: icon,
|
|
);
|
|
}
|
|
|
|
/// Shared warning-dialog shell for both purge actions — [message] is the
|
|
/// caller's job to make specific and unambiguous, since this is the only
|
|
/// thing standing between the user and an unrecoverable delete.
|
|
Future<bool> _confirmPurge({required String title, required String message}) async {
|
|
final confirmed = await showDialog<bool>(
|
|
context: context,
|
|
builder: (dialogContext) => AlertDialog(
|
|
title: Text(title),
|
|
content: Text(message),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () => Navigator.of(dialogContext).pop(false),
|
|
child: const Text('Cancel'),
|
|
),
|
|
TextButton(
|
|
style: TextButton.styleFrom(
|
|
foregroundColor: Theme.of(dialogContext).colorScheme.error,
|
|
),
|
|
onPressed: () => Navigator.of(dialogContext).pop(true),
|
|
child: const Text('Delete'),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
return confirmed ?? false;
|
|
}
|
|
|
|
/// Extra context appended to a purge warning when a cloud account is
|
|
/// connected — a purely local delete would otherwise just get silently
|
|
/// re-imported from the remote copy on the very next sync, which isn't
|
|
/// obvious from the app's normal behavior.
|
|
String _cloudSyncCaveat(AppState appState) {
|
|
if (!appState.isCloudConnected) return '';
|
|
return '\n\nThis device is connected to ${appState.activeProvider!.displayName}. The '
|
|
'deletion will be pushed there on the next sync, same as any other delete.';
|
|
}
|
|
|
|
Future<void> _purgeAllData() async {
|
|
final appState = context.read<AppState>();
|
|
final confirmed = await _confirmPurge(
|
|
title: 'Purge all data?',
|
|
message: 'This permanently deletes every vehicle, fuel entry, and receipt photo on '
|
|
"this device — starting completely fresh. This can't be undone."
|
|
'${_cloudSyncCaveat(appState)}',
|
|
);
|
|
if (!confirmed || !mounted) return;
|
|
|
|
setState(() => _busy = true);
|
|
try {
|
|
await appState.purgeAllData();
|
|
if (mounted) {
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
const SnackBar(content: Text('All data purged.')),
|
|
);
|
|
}
|
|
} finally {
|
|
if (mounted) setState(() => _busy = false);
|
|
}
|
|
}
|
|
|
|
Future<void> _pickPurgeRangeDate({required bool isStart}) async {
|
|
final now = DateTime.now();
|
|
final picked = await showDatePicker(
|
|
context: context,
|
|
initialDate: (isStart ? _purgeRangeStart : _purgeRangeEnd) ?? now,
|
|
firstDate: DateTime(2000),
|
|
lastDate: now,
|
|
);
|
|
if (picked == null) return;
|
|
setState(() {
|
|
_purgeRangeError = null;
|
|
if (isStart) {
|
|
_purgeRangeStart = picked;
|
|
} else {
|
|
_purgeRangeEnd = picked;
|
|
}
|
|
});
|
|
}
|
|
|
|
Future<void> _purgeDataInRange() async {
|
|
final start = _purgeRangeStart;
|
|
final end = _purgeRangeEnd;
|
|
if (start == null || end == null) return;
|
|
if (end.isBefore(start)) {
|
|
setState(() => _purgeRangeError = 'End date must be on or after the start date.');
|
|
return;
|
|
}
|
|
|
|
final appState = context.read<AppState>();
|
|
final confirmed = await _confirmPurge(
|
|
title: 'Purge data in range?',
|
|
message: 'This permanently deletes every fuel entry and receipt photo dated from '
|
|
'${_dateFormat.format(start)} to ${_dateFormat.format(end)}, across all '
|
|
"vehicles. Vehicles themselves aren't affected. This can't be undone."
|
|
'${_cloudSyncCaveat(appState)}',
|
|
);
|
|
if (!confirmed || !mounted) return;
|
|
|
|
setState(() => _busy = true);
|
|
try {
|
|
await appState.purgeFuelEntriesInRange(start, end);
|
|
if (mounted) {
|
|
setState(() {
|
|
_purgeRangeStart = null;
|
|
_purgeRangeEnd = null;
|
|
_purgeRangeError = null;
|
|
});
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
const SnackBar(content: Text('Fuel entries in range purged.')),
|
|
);
|
|
}
|
|
} finally {
|
|
if (mounted) setState(() => _busy = false);
|
|
}
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final appState = context.watch<AppState>();
|
|
|
|
return Scaffold(
|
|
appBar: AppBar(title: const Text('Data')),
|
|
body: ListView(
|
|
padding: const EdgeInsets.all(16),
|
|
children: [
|
|
Card(
|
|
key: OnboardingKeys.cloudStorageCard,
|
|
child: Padding(
|
|
padding: const EdgeInsets.all(16),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text('Cloud Storage', style: Theme.of(context).textTheme.titleMedium),
|
|
const SizedBox(height: 8),
|
|
if (!appState.isCloudConnected) ...[
|
|
Text(
|
|
'Connect a cloud storage account to share vehicles and fuel '
|
|
'receipts with other people, and to keep a backup off this device.',
|
|
style: Theme.of(context).textTheme.bodyMedium,
|
|
),
|
|
const SizedBox(height: 12),
|
|
if (_error != null) ...[
|
|
Text(_error!, style: TextStyle(color: Theme.of(context).colorScheme.error)),
|
|
const SizedBox(height: 8),
|
|
],
|
|
Wrap(
|
|
spacing: 8,
|
|
runSpacing: 8,
|
|
children: [
|
|
for (final provider in appState.availableProviders)
|
|
FilledButton.icon(
|
|
onPressed: _busy
|
|
? null
|
|
: () => provider is ManualCredentialCloudStorageProvider
|
|
? _connectManual(provider.id, provider.displayName)
|
|
: _connect(provider.id),
|
|
icon: const Icon(Icons.login),
|
|
label: Text('Connect ${provider.displayName}'),
|
|
),
|
|
],
|
|
),
|
|
] else ...[
|
|
Text('${appState.activeProvider!.displayName}: ${appState.cloudAccountLabel}'),
|
|
const SizedBox(height: 4),
|
|
Text(
|
|
appState.cloudFolderPath == null
|
|
? 'No folder selected yet.'
|
|
: 'Folder: ${appState.cloudFolderPath}',
|
|
style: Theme.of(context).textTheme.bodySmall,
|
|
),
|
|
const SizedBox(height: 12),
|
|
Wrap(
|
|
spacing: 8,
|
|
runSpacing: 8,
|
|
children: [
|
|
OutlinedButton.icon(
|
|
onPressed: _busy ? null : _chooseFolder,
|
|
icon: const Icon(Icons.folder_open),
|
|
label: Text(appState.cloudFolderPath == null
|
|
? 'Choose Folder'
|
|
: 'Change Folder'),
|
|
),
|
|
OutlinedButton.icon(
|
|
onPressed: (_busy || appState.cloudFolderPath == null)
|
|
? null
|
|
: _syncNow,
|
|
icon: appState.isSyncing
|
|
? const SizedBox(
|
|
height: 16,
|
|
width: 16,
|
|
child: CircularProgressIndicator(strokeWidth: 2))
|
|
: _syncNowIcon(context, appState),
|
|
label: const Text('Sync Now'),
|
|
),
|
|
TextButton.icon(
|
|
onPressed: _busy ? null : _disconnect,
|
|
icon: const Icon(Icons.logout),
|
|
label: const Text('Disconnect'),
|
|
),
|
|
],
|
|
),
|
|
const SizedBox(height: 8),
|
|
if (appState.lastSyncedAt != null)
|
|
Text(
|
|
'Last synced ${DateFormat.yMMMd().add_jm().format(appState.lastSyncedAt!)}',
|
|
style: Theme.of(context).textTheme.bodySmall,
|
|
),
|
|
if (appState.lastSyncError != null)
|
|
Padding(
|
|
padding: const EdgeInsets.only(top: 4),
|
|
child: Text(
|
|
'Last sync failed: ${appState.lastSyncError}',
|
|
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
|
),
|
|
),
|
|
],
|
|
],
|
|
),
|
|
),
|
|
),
|
|
const SizedBox(height: 16),
|
|
Card(
|
|
child: SwitchListTile(
|
|
title: const Text('Keep photos on this phone after syncing'),
|
|
subtitle: const Text(
|
|
'Otherwise, a receipt photo is removed from this device once '
|
|
"it's safely uploaded to the cloud.",
|
|
),
|
|
value: appState.keepReceiptPhotosLocally,
|
|
onChanged: (value) => context.read<AppState>().setKeepReceiptPhotosLocally(value),
|
|
),
|
|
),
|
|
const SizedBox(height: 16),
|
|
Card(
|
|
child: SwitchListTile(
|
|
title: const Text('Keep max quality images'),
|
|
subtitle: const Text(
|
|
'Otherwise, receipt photos are downscaled to a reasonable size '
|
|
'before storing — smaller cloud storage and faster syncs, with '
|
|
'no loss of legibility for a printed receipt.',
|
|
),
|
|
value: appState.keepMaxQualityReceiptPhotos,
|
|
onChanged: (value) =>
|
|
context.read<AppState>().setKeepMaxQualityReceiptPhotos(value),
|
|
),
|
|
),
|
|
const SizedBox(height: 16),
|
|
Card(
|
|
child: ExpansionTile(
|
|
title: const Text('Advanced'),
|
|
childrenPadding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
|
|
children: [
|
|
Align(
|
|
alignment: Alignment.centerLeft,
|
|
child: Text('Stale sync lock timeout', style: Theme.of(context).textTheme.titleSmall),
|
|
),
|
|
const SizedBox(height: 4),
|
|
Text(
|
|
"If another device disconnects mid-sync without releasing its lock, "
|
|
"this is how long to wait before treating it as abandoned and clearing "
|
|
"it so sync can continue.",
|
|
style: Theme.of(context).textTheme.bodySmall,
|
|
),
|
|
Slider(
|
|
value: appState.staleLockMinutes.toDouble(),
|
|
min: minStaleLockMinutes.toDouble(),
|
|
max: maxStaleLockMinutes.toDouble(),
|
|
divisions: maxStaleLockMinutes - minStaleLockMinutes,
|
|
label: '${appState.staleLockMinutes} min',
|
|
onChanged: (value) =>
|
|
context.read<AppState>().setStaleLockMinutes(value.round()),
|
|
),
|
|
Text('${appState.staleLockMinutes} minute(s)'),
|
|
const Divider(height: 32),
|
|
Text(
|
|
'Danger Zone',
|
|
style: Theme.of(context)
|
|
.textTheme
|
|
.titleMedium
|
|
?.copyWith(color: Theme.of(context).colorScheme.error),
|
|
),
|
|
const SizedBox(height: 12),
|
|
Text('Purge All Data', style: Theme.of(context).textTheme.titleSmall),
|
|
const SizedBox(height: 4),
|
|
Text(
|
|
'Deletes every vehicle, fuel entry, and receipt photo on this device '
|
|
'and starts completely fresh.',
|
|
style: Theme.of(context).textTheme.bodySmall,
|
|
),
|
|
const SizedBox(height: 8),
|
|
SizedBox(
|
|
width: double.infinity,
|
|
child: OutlinedButton.icon(
|
|
onPressed: _busy ? null : _purgeAllData,
|
|
icon: Icon(Icons.delete_forever, color: Theme.of(context).colorScheme.error),
|
|
label: Text(
|
|
'Purge All Data',
|
|
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
|
),
|
|
style: OutlinedButton.styleFrom(
|
|
side: BorderSide(color: Theme.of(context).colorScheme.error),
|
|
),
|
|
),
|
|
),
|
|
const Divider(height: 32),
|
|
Text('Purge Data by Date Range', style: Theme.of(context).textTheme.titleSmall),
|
|
const SizedBox(height: 4),
|
|
Text(
|
|
'Deletes fuel entries and receipt photos dated within a range, across '
|
|
'all vehicles. Vehicles themselves are kept.',
|
|
style: Theme.of(context).textTheme.bodySmall,
|
|
),
|
|
const SizedBox(height: 8),
|
|
Row(
|
|
children: [
|
|
Expanded(
|
|
child: OutlinedButton(
|
|
onPressed: _busy ? null : () => _pickPurgeRangeDate(isStart: true),
|
|
child: Text(
|
|
_purgeRangeStart == null
|
|
? 'Start date'
|
|
: _dateFormat.format(_purgeRangeStart!),
|
|
),
|
|
),
|
|
),
|
|
const SizedBox(width: 12),
|
|
Expanded(
|
|
child: OutlinedButton(
|
|
onPressed: _busy ? null : () => _pickPurgeRangeDate(isStart: false),
|
|
child: Text(
|
|
_purgeRangeEnd == null ? 'End date' : _dateFormat.format(_purgeRangeEnd!),
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
if (_purgeRangeError != null) ...[
|
|
const SizedBox(height: 8),
|
|
Text(
|
|
_purgeRangeError!,
|
|
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
|
),
|
|
],
|
|
const SizedBox(height: 8),
|
|
SizedBox(
|
|
width: double.infinity,
|
|
child: OutlinedButton.icon(
|
|
onPressed: (_busy || _purgeRangeStart == null || _purgeRangeEnd == null)
|
|
? null
|
|
: _purgeDataInRange,
|
|
icon: Icon(Icons.delete_forever, color: Theme.of(context).colorScheme.error),
|
|
label: Text(
|
|
'Purge Range',
|
|
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
|
),
|
|
style: OutlinedButton.styleFrom(
|
|
side: BorderSide(color: Theme.of(context).colorScheme.error),
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
class _WebDavCredentials {
|
|
final String serverUrl;
|
|
final String username;
|
|
final String password;
|
|
_WebDavCredentials({required this.serverUrl, required this.username, required this.password});
|
|
}
|
|
|
|
/// Collects the server URL/username/password a [ManualCredentialCloudStorageProvider]
|
|
/// needs, since (unlike the OAuth providers) there's no browser flow to
|
|
/// gather these instead.
|
|
class _WebDavCredentialsDialog extends StatefulWidget {
|
|
final String providerName;
|
|
const _WebDavCredentialsDialog({required this.providerName});
|
|
|
|
@override
|
|
State<_WebDavCredentialsDialog> createState() => _WebDavCredentialsDialogState();
|
|
}
|
|
|
|
class _WebDavCredentialsDialogState extends State<_WebDavCredentialsDialog> {
|
|
final _formKey = GlobalKey<FormState>();
|
|
final _serverController = TextEditingController();
|
|
final _usernameController = TextEditingController();
|
|
final _passwordController = TextEditingController();
|
|
|
|
@override
|
|
void dispose() {
|
|
_serverController.dispose();
|
|
_usernameController.dispose();
|
|
_passwordController.dispose();
|
|
super.dispose();
|
|
}
|
|
|
|
void _submit() {
|
|
if (!_formKey.currentState!.validate()) return;
|
|
Navigator.of(context).pop(_WebDavCredentials(
|
|
serverUrl: _serverController.text.trim(),
|
|
username: _usernameController.text.trim(),
|
|
password: _passwordController.text,
|
|
));
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return AlertDialog(
|
|
title: Text('Connect ${widget.providerName}'),
|
|
content: Form(
|
|
key: _formKey,
|
|
child: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
TextFormField(
|
|
controller: _serverController,
|
|
decoration: const InputDecoration(
|
|
labelText: 'Server URL',
|
|
hintText: 'https://cloud.example.com/remote.php/dav/files/me/',
|
|
),
|
|
keyboardType: TextInputType.url,
|
|
validator: (v) => (v == null || v.trim().isEmpty) ? 'Required' : null,
|
|
),
|
|
const SizedBox(height: 12),
|
|
TextFormField(
|
|
controller: _usernameController,
|
|
decoration: const InputDecoration(labelText: 'Username'),
|
|
validator: (v) => (v == null || v.trim().isEmpty) ? 'Required' : null,
|
|
),
|
|
const SizedBox(height: 12),
|
|
TextFormField(
|
|
controller: _passwordController,
|
|
decoration: const InputDecoration(labelText: 'Password'),
|
|
obscureText: true,
|
|
validator: (v) => (v == null || v.isEmpty) ? 'Required' : null,
|
|
onFieldSubmitted: (_) => _submit(),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () => Navigator.of(context).pop(),
|
|
child: const Text('Cancel'),
|
|
),
|
|
FilledButton(
|
|
onPressed: _submit,
|
|
child: const Text('Connect'),
|
|
),
|
|
],
|
|
);
|
|
}
|
|
}
|