Files
sure/mobile/lib/screens/settings_screen.dart
Lazy Bone 62dabb6971 Fix: Transaction Sync Issues & Enhanced Debugging (#632)
* Fix mobile app to fetch all transactions with pagination

The mobile app was only fetching 25 transactions per account because:
1. TransactionsService didn't pass pagination parameters to the API
2. The backend defaults to 25 records per page when no per_page is specified
3. SyncService didn't implement pagination to fetch all pages

Changes:
- Updated TransactionsService.getTransactions() to accept page and perPage parameters
- Modified the method to extract and return pagination metadata from API response
- Updated SyncService.syncFromServer() to fetch all pages (up to 100 per page)
- Added pagination loop to continue fetching until all pages are retrieved
- Enhanced logging to show pagination progress

This ensures users see all their transactions in the mobile app, not just the first 25.

* Add clear local data feature and enhanced sync logging

Added features:
1. Clear Local Data button in Settings
   - Allows users to clear all cached transactions and accounts
   - Shows confirmation dialog before clearing
   - Displays success/error feedback

2. Enhanced sync logging for debugging
   - Added detailed logs in syncFromServer to track pagination
   - Shows page-by-page progress with transaction counts
   - Logs pagination metadata (total pages, total count, etc.)
   - Tracks upsert progress every 50 transactions
   - Added clear section markers for easier log reading

3. Simplified upsertTransactionFromServer logging
   - Removed verbose debug logs to reduce noise
   - Keeps only essential error/warning logs

This will help users troubleshoot sync issues by:
- Clearing stale data and forcing a fresh sync
- Providing detailed logs to identify where sync might fail

* Fix transaction accountId parsing from API response

The mobile app was only showing 25 transactions per account because:
- The backend API returns account info in nested format: {"account": {"id": "xxx"}}
- The mobile Transaction model expected flat format: {"account_id": "xxx"}
- When parsing, accountId was always empty, so database queries by account_id returned incomplete results

Changes:
1. Updated Transaction.fromJson to handle both formats:
   - New format: {"account": {"id": "xxx", "name": "..."}}
   - Old format: {"account_id": "xxx"} (for backward compatibility)

2. Fixed classification/nature field parsing:
   - Backend sends "classification" field (income/expense)
   - Mobile uses "nature" field
   - Now handles both fields correctly

3. Added debug logging to identify empty accountId issues:
   - Logs first transaction's accountId when syncing
   - Counts and warns about transactions with empty accountId
   - Shows critical errors when trying to save with empty accountId

This ensures all transactions from the server are correctly associated with their accounts in the local database.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-01-13 09:27:39 +01:00

209 lines
6.7 KiB
Dart

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/auth_provider.dart';
import '../services/offline_storage_service.dart';
import '../services/log_service.dart';
class SettingsScreen extends StatelessWidget {
const SettingsScreen({super.key});
Future<void> _handleClearLocalData(BuildContext context) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Clear Local Data'),
content: const Text(
'This will delete all locally cached transactions and accounts. '
'Your data on the server will not be affected. '
'Are you sure you want to continue?'
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
style: TextButton.styleFrom(
foregroundColor: Theme.of(context).colorScheme.error,
),
child: const Text('Clear Data'),
),
],
),
);
if (confirmed == true && context.mounted) {
try {
final offlineStorage = OfflineStorageService();
final log = LogService.instance;
log.info('Settings', 'Clearing all local data...');
await offlineStorage.clearAllData();
log.info('Settings', 'Local data cleared successfully');
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Local data cleared successfully. Pull to refresh to sync from server.'),
backgroundColor: Colors.green,
duration: Duration(seconds: 3),
),
);
}
} catch (e) {
final log = LogService.instance;
log.error('Settings', 'Failed to clear local data: $e');
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Failed to clear local data: $e'),
backgroundColor: Colors.red,
duration: const Duration(seconds: 3),
),
);
}
}
}
}
Future<void> _handleLogout(BuildContext context) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Sign Out'),
content: const Text('Are you sure you want to sign out?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
child: const Text('Sign Out'),
),
],
),
);
if (confirmed == true && context.mounted) {
final authProvider = Provider.of<AuthProvider>(context, listen: false);
await authProvider.logout();
}
}
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final authProvider = Provider.of<AuthProvider>(context);
return Scaffold(
appBar: AppBar(
title: const Text('Settings'),
),
body: ListView(
children: [
// User info section
Container(
padding: const EdgeInsets.all(16),
child: Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
CircleAvatar(
radius: 30,
backgroundColor: colorScheme.primary,
child: Text(
authProvider.user?.displayName[0].toUpperCase() ?? 'U',
style: TextStyle(
fontSize: 24,
color: colorScheme.onPrimary,
fontWeight: FontWeight.bold,
),
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
authProvider.user?.displayName ?? 'User',
style: Theme.of(context).textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Text(
authProvider.user?.email ?? '',
style: TextStyle(
color: colorScheme.onSurfaceVariant,
),
),
],
),
),
],
),
],
),
),
),
),
// App version
const ListTile(
leading: Icon(Icons.info_outline),
title: Text('App Version'),
subtitle: Text('1.0.0'),
),
const Divider(),
// Data Management Section
const Padding(
padding: EdgeInsets.fromLTRB(16, 16, 16, 8),
child: Text(
'Data Management',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: Colors.grey,
),
),
),
// Clear local data button
ListTile(
leading: const Icon(Icons.delete_outline),
title: const Text('Clear Local Data'),
subtitle: const Text('Remove all cached transactions and accounts'),
onTap: () => _handleClearLocalData(context),
),
const Divider(),
// Sign out button
Padding(
padding: const EdgeInsets.all(16),
child: ElevatedButton.icon(
onPressed: () => _handleLogout(context),
icon: const Icon(Icons.logout),
label: const Text('Sign Out'),
style: ElevatedButton.styleFrom(
backgroundColor: colorScheme.error,
foregroundColor: colorScheme.onError,
),
),
),
],
),
);
}
}