import 'dart:io'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; import 'package:provider/provider.dart'; import '../screens/confirm_fuel_entry_screen.dart'; import '../services/app_state.dart'; import '../services/ocr_service.dart'; import '../services/receipt_parser.dart'; import 'image_source_sheet.dart'; /// Long edge and JPEG quality a receipt photo is downscaled to unless /// "keep max quality" is on — a receipt is a photo of small printed text, /// not something that benefits from a multi-megapixel original, and this /// keeps typical files in the low hundreds of KB instead of several MB. const receiptImageMaxDimension = 1600.0; const receiptImageQuality = 70; /// Shared by [VehicleDetailScreen]'s "Log Fuel Receipt" button and the /// Receipts tab's "+" action: pick a photo, OCR it, and — unless the /// receipt looks like it's from outside Missouri, in which case the user /// gets a chance to back out first — hand off to [ConfirmFuelEntryScreen] /// for [vehicleId]. Future captureReceiptForVehicle(BuildContext context, String vehicleId) async { final source = await chooseImageSource(context, heading: 'Receipt From'); if (source == null || !context.mounted) return; final keepMaxQuality = context.read().keepMaxQualityReceiptPhotos; final picker = ImagePicker(); // Raised *before* the camera/gallery opens rather than after it returns. // [ImagePicker.pickImage] doesn't complete when the camera closes — it // also downscales the captured photo (several MB straight off the // sensor), which takes seconds on a busy device. With the progress // shown only afterward, that whole stretch left the user staring at an // unchanged Receipts list with no sign anything was happening, which // reads as "the capture did nothing" — and tapping away during it // genuinely does abandon the capture. var progressShowing = false; void showProgress() { if (progressShowing || !context.mounted) return; progressShowing = true; showDialog( context: context, barrierDismissible: false, builder: (_) => const _ReceiptProgressDialog(), ); } void hideProgress() { if (!progressShowing || !context.mounted) return; progressShowing = false; Navigator.of(context).pop(); } showProgress(); XFile? photo; try { photo = await picker.pickImage( source: source, imageQuality: keepMaxQuality ? null : receiptImageQuality, maxWidth: keepMaxQuality ? null : receiptImageMaxDimension, maxHeight: keepMaxQuality ? null : receiptImageMaxDimension, ); } catch (e) { hideProgress(); if (context.mounted) { final sourceLabel = source == ImageSource.camera ? 'camera' : 'photo library'; ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Could not open $sourceLabel: $e')), ); } return; } // Cancelled (backed out of the camera, or didn't confirm the shot) — // nothing to say about that, it was deliberate. if (photo == null) { hideProgress(); return; } final imageFile = File(photo.path); if (!context.mounted) return; final ocrService = OcrService(); String recognizedText = ''; try { recognizedText = await ocrService.recognizeText(imageFile); } catch (_) { recognizedText = ''; } finally { ocrService.dispose(); } final parsed = ReceiptParser.parse(recognizedText); if (!context.mounted) return; hideProgress(); final state = parsed.state; if (state != null && state != 'MO') { final proceed = await _confirmNonMissouriPurchase(context, state); if (!proceed || !context.mounted) return; } if (context.mounted) { Navigator.of(context).push( MaterialPageRoute( builder: (_) => ConfirmFuelEntryScreen( vehicleId: vehicleId, imageFile: imageFile, parsed: parsed, ), ), ); } } /// Shown from the moment the camera/gallery is opened until the parsed /// receipt is ready to review. Deliberately says what's happening rather /// than showing a bare spinner: the wait here is mostly downscaling and /// reading the photo, which is long enough on a slow device that an /// unexplained spinner invites tapping away mid-capture. class _ReceiptProgressDialog extends StatelessWidget { const _ReceiptProgressDialog(); @override Widget build(BuildContext context) { return PopScope( // Backing out here wouldn't cancel the underlying capture, it would // just hide it and strand the user. canPop: false, child: Dialog( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 28, vertical: 32), child: Column( mainAxisSize: MainAxisSize.min, children: [ const CircularProgressIndicator(), const SizedBox(height: 20), Text('Reading your receipt…', style: Theme.of(context).textTheme.titleSmall), const SizedBox(height: 6), Text( 'This can take a few seconds.', textAlign: TextAlign.center, style: Theme.of(context).textTheme.bodySmall?.copyWith( color: Theme.of(context).colorScheme.onSurfaceVariant, ), ), ], ), ), ), ); } } /// Missouri's fuel tax refund only applies to fuel bought in Missouri — /// warn if the receipt's address is somewhere else, and let the user /// decide whether to log it anyway (e.g. it might still be worth tracking /// for other reasons even if it won't qualify for a refund). Future _confirmNonMissouriPurchase(BuildContext context, String stateCode) async { final stateName = usStateNames[stateCode] ?? stateCode; final proceed = await showDialog( context: context, builder: (context) => AlertDialog( title: const Text('Non-Missouri Purchase'), content: Text( 'This receipt looks like it\'s from a gas station in $stateName. ' 'The Missouri fuel tax refund only applies to fuel purchased in ' 'Missouri.\n\nDo you still want to add this entry?', ), actions: [ TextButton(onPressed: () => Navigator.of(context).pop(false), child: const Text('No')), FilledButton(onPressed: () => Navigator.of(context).pop(true), child: const Text('Yes')), ], ), ); return proceed ?? false; }