-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtemp.txt
More file actions
1772 lines (1571 loc) · 49.9 KB
/
Copy pathtemp.txt
File metadata and controls
1772 lines (1571 loc) · 49.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// lib/core/models/client_models.dart
// Add these classes to your existing client_models.dart file
import 'package:equatable/equatable.dart';
/// Represents a document uploaded by the user before processing
class UploadedDocument extends Equatable {
final String id;
final String fileName;
final String filePath;
final String? password;
final int ownerParticipantId;
final FinancialInstitution institution;
final DateTime uploadedAt;
const UploadedDocument({
required this.id,
required this.fileName,
required this.filePath,
this.password,
required this.ownerParticipantId,
required this.institution,
required this.uploadedAt,
});
@override
List<Object?> get props => [
id,
fileName,
filePath,
password,
ownerParticipantId,
institution,
uploadedAt,
];
}
/// Financial institutions supported by the app
enum FinancialInstitution {
hsbc,
equity,
mpesa,
custom;
String get displayName {
switch (this) {
case FinancialInstitution.hsbc:
return 'HSBC';
case FinancialInstitution.equity:
return 'Equity';
case FinancialInstitution.mpesa:
return 'M-PESA';
case FinancialInstitution.custom:
return 'Custom';
}
}
String get logoPath {
switch (this) {
case FinancialInstitution.hsbc:
return 'assets/banks/hsbc.png';
case FinancialInstitution.equity:
return 'assets/banks/equity.png';
case FinancialInstitution.mpesa:
return 'assets/banks/mpesa.png';
case FinancialInstitution.custom:
return 'assets/banks/custom.png';
}
}
}
/// Represents a transaction extracted from a PDF but not yet saved to database
class ParsedTransaction extends Equatable {
final String id; // Temporary ID for UI tracking
final DateTime date;
final String vendorName;
final double amount;
final String? category;
final String? account;
final String? reason;
final bool useMemory; // Maps to "Use Memory" checkbox
const ParsedTransaction({
required this.id,
required this.date,
required this.vendorName,
required this.amount,
this.category,
this.account,
this.reason,
this.useMemory = false,
});
ParsedTransaction copyWith({
String? id,
DateTime? date,
String? vendorName,
double? amount,
String? category,
String? account,
String? reason,
bool? useMemory,
}) {
return ParsedTransaction(
id: id ?? this.id,
date: date ?? this.date,
vendorName: vendorName ?? this.vendorName,
amount: amount ?? this.amount,
category: category ?? this.category,
account: account ?? this.account,
reason: reason ?? this.reason,
useMemory: useMemory ?? this.useMemory,
);
}
@override
List<Object?> get props => [
id,
date,
vendorName,
amount,
category,
account,
reason,
useMemory,
];
}
/// Result of parsing a document
class ParseResult extends Equatable {
final bool success;
final String? errorMessage;
final List<ParsedTransaction> transactions;
final UploadedDocument document;
const ParseResult({
required this.success,
this.errorMessage,
required this.transactions,
required this.document,
});
@override
List<Object?> get props => [success, errorMessage, transactions, document];
}
/// Validation result for document parseability
class ValidationResult extends Equatable {
final bool canParse;
final String? errorMessage;
final List<String> missingCheckpoints;
const ValidationResult({
required this.canParse,
this.errorMessage,
this.missingCheckpoints = const [],
});
const ValidationResult.success()
: canParse = true,
errorMessage = null,
missingCheckpoints = const [];
const ValidationResult.failure({
required String error,
List<String> missing = const [],
}) : canParse = false,
errorMessage = error,
missingCheckpoints = missing;
@override
List<Object?> get props => [canParse, errorMessage, missingCheckpoints];
}
// Existing models (Template, Account, Category, etc.) remain here...
==========================================================================================
// lib/core/services/parser/custom_parser.dart
import 'dart:io';
import 'package:uuid/uuid.dart';
import '../../models/client_models.dart';
import 'parser_interface.dart';
/// Parser for custom/generic bank statements
///
/// This parser attempts to handle statements from unknown banks
/// by looking for common patterns across different statement formats.
///
/// Expected Minimum Structure:
/// - Some form of date column (various formats accepted)
/// - Description/vendor column
/// - Amount column (may be combined or separate debit/credit)
///
/// This parser is more lenient and uses heuristics to identify:
/// - Transaction tables (by finding repeating patterns)
/// - Date formats (tries multiple common formats)
/// - Amount formats (handles various currency symbols and separators)
class CustomParser implements StatementParser {
@override
FinancialInstitution get institution => FinancialInstitution.custom;
/// Checkpoints to verify in PDF:
/// 1. At least one table-like structure
/// 2. Repeating date patterns
/// 3. Repeating number patterns (amounts)
/// 4. Minimum 3 columns detected
///
/// This is more lenient than institution-specific parsers
@override
Future<ValidationResult> validateDocument(
File pdfFile, {
String? password,
}) async {
// TODO: Implement custom validation
//
// Strategy:
// 1. Extract all text
// 2. Look for tabular data (aligned columns, repeating patterns)
// 3. Try to identify date column (test multiple formats)
// 4. Try to identify amount column (look for currency patterns)
// 5. If both found, consider it parseable
return const ValidationResult.success();
}
@override
Future<ParseResult> parseDocument(
File pdfFile,
UploadedDocument documentMetadata, {
String? password,
}) async {
// TODO: Implement custom parsing
//
// Strategy:
// 1. Extract table data using heuristics
// 2. Identify which columns contain dates, vendors, amounts
// 3. Parse each row using flexible patterns
// 4. Apply confidence scoring (warn user about uncertain parses)
// 5. Return best-effort results
return ParseResult(
success: true,
transactions: _generateSampleTransactions(documentMetadata),
document: documentMetadata,
);
}
@override
Future<bool> unlockPdf(File pdfFile, String? password) async {
return true;
}
@override
bool containsInstitutionMarkers(String pdfText) {
// Custom parser doesn't look for specific markers
// Just check if it looks like a financial document
final financialKeywords = [
'statement',
'account',
'balance',
'transaction',
'debit',
'credit',
'date',
];
final lowerText = pdfText.toLowerCase();
return financialKeywords.any((keyword) => lowerText.contains(keyword));
}
@override
List<List<String>> extractTableData(String pdfText) {
// TODO: Implement intelligent table detection
// Look for patterns of aligned text that repeats
return [];
}
@override
String normalizeVendorName(String rawVendor) {
// Generic cleaning
return rawVendor
.trim()
.replaceAll(RegExp(r'\s+'), ' '); // Normalize whitespace
}
@override
DateTime? parseDate(String dateString) {
// Try multiple common date formats
final formats = [
_tryParseDDMMYYYY,
_tryParseDDMMMYYYY,
_tryParseYYYYMMDD,
_tryParseMMDDYYYY,
];
for (final format in formats) {
final result = format(dateString);
if (result != null) return result;
}
return null;
}
DateTime? _tryParseDDMMYYYY(String dateString) {
try {
final parts = dateString.split(RegExp(r'[/\-.]'));
if (parts.length != 3) return null;
return DateTime(
int.parse(parts[2]),
int.parse(parts[1]),
int.parse(parts[0]),
);
} catch (e) {
return null;
}
}
DateTime? _tryParseDDMMMYYYY(String dateString) {
final months = {
'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4,
'may': 5, 'jun': 6, 'jul': 7, 'aug': 8,
'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12,
};
try {
final parts = dateString.toLowerCase().split(' ');
if (parts.length != 3) return null;
final day = int.parse(parts[0]);
final month = months[parts[1].substring(0, 3)];
final year = int.parse(parts[2]);
if (month == null) return null;
return DateTime(year, month, day);
} catch (e) {
return null;
}
}
DateTime? _tryParseYYYYMMDD(String dateString) {
try {
final parts = dateString.split(RegExp(r'[/\-.]'));
if (parts.length != 3) return null;
return DateTime(
int.parse(parts[0]),
int.parse(parts[1]),
int.parse(parts[2]),
);
} catch (e) {
return null;
}
}
DateTime? _tryParseMMDDYYYY(String dateString) {
try {
final parts = dateString.split(RegExp(r'[/\-.]'));
if (parts.length != 3) return null;
return DateTime(
int.parse(parts[2]),
int.parse(parts[0]),
int.parse(parts[1]),
);
} catch (e) {
return null;
}
}
@override
double? parseAmount(String amountString) {
// Remove all currency symbols and separators
final cleaned = amountString
.replaceAll(RegExp(r'[^\d.\-+]'), '')
.trim();
try {
return double.parse(cleaned);
} catch (e) {
return null;
}
}
List<ParsedTransaction> _generateSampleTransactions(
UploadedDocument document,
) {
final uuid = const Uuid();
return List.generate(
8,
(index) => ParsedTransaction(
id: uuid.v4(),
date: DateTime.now().subtract(Duration(days: index * 2)),
vendorName: 'Greggs PLC',
amount: -2.90,
useMemory: false,
),
);
}
}
==========================================================================================
// lib/core/services/document_service.dart
import 'dart:io';
import 'package:logging/logging.dart';
import 'package:uuid/uuid.dart';
import '../models/client_models.dart';
import 'parser/parser_factory.dart';
import 'parser/parser_interface.dart';
/// Service for handling document upload, validation, and parsing
class DocumentService {
final Logger _logger = Logger('DocumentService');
final Uuid _uuid = const Uuid();
/// Creates an UploadedDocument from file metadata
UploadedDocument createUploadedDocument({
required String fileName,
required String filePath,
String? password,
required int ownerParticipantId,
required FinancialInstitution institution,
}) {
return UploadedDocument(
id: _uuid.v4(),
fileName: fileName,
filePath: filePath,
password: password,
ownerParticipantId: ownerParticipantId,
institution: institution,
uploadedAt: DateTime.now(),
);
}
/// Validates that a document can be parsed by the selected parser
Future<ValidationResult> validateDocument(
UploadedDocument document,
) async {
try {
_logger.info('Validating document: ${document.fileName}');
final file = File(document.filePath);
if (!await file.exists()) {
return const ValidationResult.failure(
error: 'File not found. Please upload the document again.',
);
}
// Get appropriate parser
final parser = ParserFactory.getParser(document.institution);
// Validate with parser
final result = await parser.validateDocument(
file,
password: document.password,
);
if (result.canParse) {
_logger.info('Document validation successful: ${document.fileName}');
} else {
_logger.warning(
'Document validation failed: ${document.fileName}. '
'Reason: ${result.errorMessage}',
);
}
return result;
} catch (e, st) {
_logger.severe('Error validating document', e, st);
return ValidationResult.failure(
error: 'An error occurred while validating the document: $e',
);
}
}
/// Parses a document and extracts transactions
Future<ParseResult> parseDocument(
UploadedDocument document,
) async {
try {
_logger.info('Parsing document: ${document.fileName}');
final file = File(document.filePath);
if (!await file.exists()) {
return ParseResult(
success: false,
errorMessage: 'File not found. Please upload the document again.',
transactions: const [],
document: document,
);
}
// Get appropriate parser
final parser = ParserFactory.getParser(document.institution);
// Parse document
final result = await parser.parseDocument(
file,
document,
password: document.password,
);
if (result.success) {
_logger.info(
'Document parsed successfully: ${document.fileName}. '
'Found ${result.transactions.length} transactions.',
);
} else {
_logger.warning(
'Document parsing failed: ${document.fileName}. '
'Reason: ${result.errorMessage}',
);
}
return result;
} catch (e, st) {
_logger.severe('Error parsing document', e, st);
return ParseResult(
success: false,
errorMessage: 'An error occurred while parsing the document: $e',
transactions: const [],
document: document,
);
}
}
/// Cleans up a document file from storage
Future<void> cleanupDocument(UploadedDocument document) async {
try {
final file = File(document.filePath);
if (await file.exists()) {
await file.delete();
_logger.info('Cleaned up document: ${document.fileName}');
}
} catch (e, st) {
_logger.warning('Failed to cleanup document: ${document.fileName}', e, st);
// Non-critical error, don't throw
}
}
/// Validates that a file is a valid PDF
bool isValidPdf(String filePath) {
try {
final file = File(filePath);
if (!file.existsSync()) return false;
// Check file extension
if (!filePath.toLowerCase().endsWith('.pdf')) return false;
// Read first few bytes to check PDF header
final bytes = file.readAsBytesSync();
if (bytes.length < 5) return false;
// PDF files start with %PDF
final header = String.fromCharCodes(bytes.take(4));
return header == '%PDF';
} catch (e) {
_logger.warning('Error checking PDF validity: $e');
return false;
}
}
/// Gets a human-readable file size
String getFileSize(String filePath) {
try {
final file = File(filePath);
final bytes = file.lengthSync();
if (bytes < 1024) return '$bytes B';
if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
} catch (e) {
return 'Unknown';
}
}
}
==========================================================================================
// lib/features/home/home_viewmodel.dart
import 'package:flutter/foundation.dart';
import 'package:logging/logging.dart';
import '../../core/context.dart';
import '../../core/models/client_models.dart';
import '../../core/models/models.dart' as models;
import '../../core/services/document_service.dart';
import '../../core/services/participant_service.dart';
import '../../core/services/budget_service.dart';
class HomeViewModel extends ChangeNotifier {
final DocumentService _documentService;
final ParticipantService _participantService;
final BudgetService _budgetService;
final AppContext _appContext;
final Logger _logger = Logger('HomeViewModel');
// State
List<UploadedDocument> _uploadedDocuments = [];
List<ParsedTransaction> _extractedTransactions = [];
List<models.Participant> _participants = [];
List<models.Template> _templateHistory = [];
bool _isLoading = false;
bool _hasRunAudit = false;
String? _errorMessage;
HomeViewModel({
required DocumentService documentService,
required ParticipantService participantService,
required BudgetService budgetService,
required AppContext appContext,
}) : _documentService = documentService,
_participantService = participantService,
_budgetService = budgetService,
_appContext = appContext {
_initialize();
}
// Getters
List<UploadedDocument> get uploadedDocuments => _uploadedDocuments;
List<ParsedTransaction> get extractedTransactions => _extractedTransactions;
List<models.Participant> get participants => _participants;
List<models.Template> get templateHistory => _templateHistory;
bool get isLoading => _isLoading;
bool get hasRunAudit => _hasRunAudit;
String? get errorMessage => _errorMessage;
bool get hasDocuments => _uploadedDocuments.isNotEmpty;
bool get hasTransactions => _extractedTransactions.isNotEmpty;
int? get currentParticipantId => _appContext.participantId;
Future<void> _initialize() async {
await loadParticipants();
await loadTemplateHistory();
}
/// Loads all participants from the database
Future<void> loadParticipants() async {
try {
_participants = await _participantService.getAllParticipants();
notifyListeners();
} catch (e, st) {
_logger.severe('Error loading participants', e, st);
}
}
/// Loads template history for the current user
Future<void> loadTemplateHistory() async {
try {
_templateHistory = await _budgetService.templateService.getAllTemplates();
notifyListeners();
} catch (e, st) {
_logger.severe('Error loading template history', e, st);
}
}
/// Adds a document to the upload queue
Future<bool> addDocument({
required String fileName,
required String filePath,
String? password,
required int ownerParticipantId,
required FinancialInstitution institution,
}) async {
try {
_errorMessage = null;
// Validate PDF
if (!_documentService.isValidPdf(filePath)) {
_errorMessage = 'Invalid PDF file. Please select a valid PDF document.';
notifyListeners();
return false;
}
// Create document
final document = _documentService.createUploadedDocument(
fileName: fileName,
filePath: filePath,
password: password,
ownerParticipantId: ownerParticipantId,
institution: institution,
);
// Validate document can be parsed
_isLoading = true;
notifyListeners();
final validationResult = await _documentService.validateDocument(document);
_isLoading = false;
if (!validationResult.canParse) {
_errorMessage = validationResult.errorMessage ??
'Document could not be understood. Please check:\n'
'${validationResult.missingCheckpoints.join('\n')}';
notifyListeners();
return false;
}
// Add to list
_uploadedDocuments.add(document);
_logger.info('Document added: $fileName');
notifyListeners();
return true;
} catch (e, st) {
_logger.severe('Error adding document', e, st);
_errorMessage = 'Failed to add document: $e';
_isLoading = false;
notifyListeners();
return false;
}
}
/// Removes a document from the upload queue
void removeDocument(String documentId) {
final document = _uploadedDocuments.firstWhere(
(doc) => doc.id == documentId,
orElse: () => throw Exception('Document not found'),
);
_uploadedDocuments.removeWhere((doc) => doc.id == documentId);
_documentService.cleanupDocument(document);
_logger.info('Document removed: ${document.fileName}');
notifyListeners();
}
/// Runs audit on all uploaded documents
Future<void> runAudit() async {
if (_uploadedDocuments.isEmpty) {
_errorMessage = 'Please upload at least one document before running audit.';
notifyListeners();
return;
}
try {
_isLoading = true;
_errorMessage = null;
_extractedTransactions.clear();
notifyListeners();
// Parse each document
for (final document in _uploadedDocuments) {
final parseResult = await _documentService.parseDocument(document);
if (parseResult.success) {
_extractedTransactions.addAll(parseResult.transactions);
} else {
_logger.warning(
'Failed to parse ${document.fileName}: ${parseResult.errorMessage}',
);
}
}
_hasRunAudit = true;
_isLoading = false;
_logger.info('Audit completed. Found ${_extractedTransactions.length} transactions.');
notifyListeners();
} catch (e, st) {
_logger.severe('Error running audit', e, st);
_errorMessage = 'Failed to run audit: $e';
_isLoading = false;
notifyListeners();
}
}
/// Updates a parsed transaction
void updateTransaction(ParsedTransaction updatedTransaction) {
final index = _extractedTransactions.indexWhere(
(t) => t.id == updatedTransaction.id,
);
if (index != -1) {
_extractedTransactions[index] = updatedTransaction;
notifyListeners();
}
}
/// Toggles the "Use Memory" checkbox for a transaction
void toggleUseMemory(String transactionId) {
final index = _extractedTransactions.indexWhere((t) => t.id == transactionId);
if (index != -1) {
final transaction = _extractedTransactions[index];
_extractedTransactions[index] = transaction.copyWith(
useMemory: !transaction.useMemory,
);
notifyListeners();
}
}
/// Refreshes the extracted transactions (re-parses documents)
Future<void> refreshTransactions() async {
await runAudit();
}
/// Clears all extracted transactions
void clearTransactions() {
_extractedTransactions.clear();
_hasRunAudit = false;
notifyListeners();
}
/// Clears all documents and resets state
void reset() {
for (final doc in _uploadedDocuments) {
_documentService.cleanupDocument(doc);
}
_uploadedDocuments.clear();
_extractedTransactions.clear();
_hasRunAudit = false;
_errorMessage = null;
notifyListeners();
}
/// Deletes a template from history
Future<void> deleteTemplate(int templateId) async {
try {
final success = await _budgetService.templateService.deleteTemplate(templateId);
if (success) {
_templateHistory.removeWhere((t) => t.templateId == templateId);
_logger.info('Template deleted: $templateId');
notifyListeners();
}
} catch (e, st) {
_logger.severe('Error deleting template', e, st);
_errorMessage = 'Failed to delete template: $e';
notifyListeners();
}
}
@override
void dispose() {
// Cleanup any temporary files
for (final doc in _uploadedDocuments) {
_documentService.cleanupDocument(doc);
}
super.dispose();
}
}
==========================================================================================
// lib/features/home/home_view.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/theme/app_theme.dart';
import '../../shared/widgets/app_header.dart';
import 'home_viewmodel.dart';
import 'widgets/document_ingestion_widget.dart';
import 'widgets/extracted_transactions_widget.dart';
import 'widgets/side_panel.dart';
class HomeView extends StatelessWidget {
const HomeView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final viewModel = context.watch<HomeViewModel>();
final mediaQuery = MediaQuery.of(context);
final isWideScreen = mediaQuery.size.width > 1024;
return Scaffold(
backgroundColor: AppTheme.backgroundColor,
body: SafeArea(
child: Column(
children: [
const AppHeader(
subtitle: 'Document Analysis & Transaction Extraction',
),
Expanded(
child: isWideScreen
? _buildWideScreenLayout(context, viewModel)
: _buildNarrowScreenLayout(context, viewModel),
),
],
),
),
);
}
Widget _buildWideScreenLayout(
BuildContext context,
HomeViewModel viewModel,
) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Main content area
Expanded(
flex: 3,
child: _buildMainContent(context, viewModel),
),
// Side panel
Container(
width: 350,
decoration: BoxDecoration(
color: AppTheme.surface,
border: Border(
left: BorderSide(color: AppTheme.border, width: 1),
),
),
child: const SidePanel(),
),
],
);
}
Widget _buildNarrowScreenLayout(
BuildContext context,
HomeViewModel viewModel,
) {
return _buildMainContent(context, viewModel);
}
Widget _buildMainContent(
BuildContext context,
HomeViewModel viewModel,
) {
return SingleChildScrollView(
padding: const EdgeInsets.all(AppTheme.spacingLg),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Data handling notice
_buildDataHandlingNotice(context),
const SizedBox(height: AppTheme.spacingLg),
// Document ingestion
const DocumentIngestionWidget(),
const SizedBox(height: AppTheme.spacingLg),
// Extracted transactions (only shown after audit)
if (viewModel.hasRunAudit) ...[
const ExtractedTransactionsWidget(),
],
// Error message
if (viewModel.errorMessage != null) ...[
const SizedBox(height: AppTheme.spacingMd),
_buildErrorMessage(context, viewModel.errorMessage!),
],
],
),
);
}
Widget _buildDataHandlingNotice(BuildContext context) {
return Row(
children: [
Icon(
Icons.shield_outlined,
color: AppTheme.success,
size: 20,
),
const SizedBox(width: AppTheme.spacingXs),
Expanded(
child: RichText(
text: TextSpan(
style: AppTheme.bodySmall.copyWith(
color: AppTheme.textSecondary,
),
children: [
const TextSpan(
text: 'Your financial documents never leave your device. ',
),
TextSpan(
text: 'Learn more about Budget Audit data handling here',
style: TextStyle(
color: AppTheme.primaryPink,
decoration: TextDecoration.underline,
),
),
],
),
),
),
],
);
}
Widget _buildErrorMessage(BuildContext context, String message) {
return Container(
padding: const EdgeInsets.all(AppTheme.spacingMd),
decoration: BoxDecoration(
color: AppTheme.error.withOpacity(0.1),
border: Border.all(color: AppTheme.error, width: 1),
borderRadius: BorderRadius.circular(AppTheme.radiusMd),
),