# Project Context Log

## [2025-08-19 10:00] - Initial Setup & Context Discussion

- Initial project directory structure reviewed.
- Agreed to use this file (`PROJECT_CONTEXT.md`) as a log/journal for our collaboration.
- Decided on a format for entries: `## [YYYY-MM-DD HH:MM] - Brief Description of Key Info/Topic`.
- This file will be updated after each significant discussion or task completion to capture context, decisions, or important notes.
- Next steps: Begin working on specific tasks within the project. New entries will be added here as needed.

## [2025-08-19 10:15] - Firefly III Transaction Submission API Research

- Researched Firefly III API documentation for submitting transactions.
- Found the correct endpoint: `POST /api/v1/transactions`.
- Identified required and optional JSON fields for a transaction.
- Obtained an example `curl` command for submitting a transaction.

**Key Information:**
- **Endpoint:** `POST /api/v1/transactions`
- **Required Headers:**
  - `Authorization: Bearer YOUR_ACCESS_TOKEN`
  - `Content-Type: application/json`
- **Example JSON Payload:**
  ```json
  {
    "transactions": [
      {
        "type": "withdrawal",
        "date": "2023-10-01",
        "amount": "100.00",
        "description": "Groceries",
        "source_id": 1,
        "destination_id": 2,
        "category_id": 3,
        "budget_id": 4
      }
    ]
  }
  ```
- **Example `curl` Command:**
  ```bash
  curl -X POST "https://your-firefly-iii-instance.com/api/v1/transactions" \
    -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
    "transactions": [
      {
        "type": "withdrawal",
        "date": "2023-10-01",
        "amount": "100.00",
        "description": "Groceries",
        "source_id": 1,
        "destination_id": 2,
        "category_id": 3,
        "budget_id": 4
      }
    ]
  }'
  ```
  *(Note: Replace `YOUR_ACCESS_TOKEN` and the instance URL with actual values)*

## [2025-08-19 10:30] - Firefly III Accounts Retrieval API Research

- Researched Firefly III API documentation for retrieving accounts.
- Found the correct endpoint: `GET /api/v1/accounts`.
- Learned how to filter accounts by type (e.g., `asset`, `expense`, `revenue`).
- Obtained example `curl` commands for fetching accounts.

**Key Information:**
- **Endpoint:** `GET /api/v1/accounts`
- **Required Headers:**
  - `Authorization: Bearer YOUR_ACCESS_TOKEN`
  - `Accept: application/json`
- **Query Parameters:**
  - `type`: Filter accounts by type (`asset`, `expense`, `revenue`, `liability`, `loan`, `debt`, `mortgage`).
  - `page`: For pagination.
- **Example `curl` Commands:**
  ```bash
  # Get all accounts
  curl -X GET "https://your-firefly-iii-instance.com/api/v1/accounts" \
    -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
    -H "Accept: application/json"

  # Get only 'asset' accounts (commonly used as source accounts)
  curl -X GET "https://your-firefly-iii-instance.com/api/v1/accounts?type=asset" \
    -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
    -H "Accept: application/json"

  # Get 'expense' accounts (commonly used as destination for withdrawals)
  curl -X GET "https://your-firefly-iii-instance.com/api/v1/accounts?type=expense" \
    -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
    -H "Accept: application/json"
  ```
- **Response Structure:**
  The response includes a `data` array where each account object has an `id` and `attributes` containing details like `name` and `type`.

## [2025-08-19 10:45] - Create `curl_scripts` Directory and Scripts

- Created a new directory `curl_scripts` to store our API interaction scripts.
- Created `get_accounts.sh`:
  - Script to fetch accounts from Firefly III using `GET /api/v1/accounts`.
  - Includes examples for fetching all accounts, 'asset' accounts (source), and 'expense' accounts (destination).
  - Uses environment variables for URL and token for security.
- Created `submit_dummy_transaction.sh`:
  - Script to submit a dummy transaction to Firefly III using `POST /api/v1/transactions`.
  - Uses environment variables for URL, token, source ID, and destination ID.
  - Includes basic error handling and response code checking.
- Made both scripts executable with `chmod +x`.

## [2025-08-19 11:00] - Update `get_accounts.sh` Script for Filtering

- Updated `curl_scripts/get_accounts.sh` to accept an optional `ACCOUNT_TYPE` environment variable.
- This allows fetching specific types of accounts (e.g., `asset`, `expense`) to reduce output clutter.
- Example usage:
  ```bash
  YOUR_FIREFLY_III_URL="..." YOUR_ACCESS_TOKEN="..." ACCOUNT_TYPE="asset" ./curl_scripts/get_accounts.sh
  ```
- Added debug output to show the final URL being used by the script.
- Re-applied executable permissions to the updated script.

## [2025-08-19 11:15] - Clarify Account Types for 'Receipt' Context

- Discussed the specific account types needed for submitting a 'receipt' (struk) transaction.
- **For a 'receipt' representing incoming funds/purchase:**
  - **`source_id`**: Should be an account of type **`revenue`** (e.g., Salary, Gift). This is where the money is considered to come from.
  - **`destination_id`**: Should be an account of type **`asset`** (e.g., Checking Account, Cash Wallet). This is where the money ends up.
- Updated understanding for using `get_accounts.sh`:
  - Run once with `ACCOUNT_TYPE="revenue"` to find a suitable `source_id`.
  - Run once with `ACCOUNT_TYPE="asset"` to find a suitable `destination_id`.
- These IDs will then be used with `submit_dummy_transaction.sh` to create the transaction record in Firefly III.

## [2025-08-19 11:30] - Fix Bug in `submit_dummy_transaction.sh`

- Identified and fixed a bug in `curl_scripts/submit_dummy_transaction.sh` that caused error `line 25: Dummy: command not found`.
- The issue was due to an incorrect use of a multiline string variable assignment (`read -r -d '' ... << EOM`).
- The script was updated to build the JSON payload directly within the `curl` command using `-d` with proper escaping. This is a more robust and portable method.
- Re-applied executable permissions to the corrected script.

## [2025-08-19 11:45] - Fix Account Type Mismatch & Add Transaction Type Flexibility

- Diagnosed the `HTTP Code: 000` and subsequent Firefly III error `[a] Could not find a valid source account...`.
- Root cause: The transaction `type` in `submit_dummy_transaction.sh` was hardcoded to `withdrawal`, which is incompatible with using a `revenue` account as `source_id`.
- **Solution Implemented:**
  - Updated `curl_scripts/submit_dummy_transaction.sh` to accept an optional `TRANSACTION_TYPE` environment variable.
  - Default value for `TRANSACTION_TYPE` is now set to `deposit`, which is the correct type when `source_id` is `revenue` and `destination_id` is `asset`.
  - Example usage for 'receipt' context:
    ```bash
    YOUR_FIREFLY_III_URL="..." YOUR_ACCESS_TOKEN="..." SOURCE_ACCOUNT_ID=92 DESTINATION_ACCOUNT_ID=1 TRANSACTION_TYPE="deposit" ./curl_scripts/submit_dummy_transaction.sh
    ```
- This change provides more flexibility for testing different transaction types and ensures compatibility with the intended account types for a 'receipt'.
- Re-applied executable permissions to the updated script.

## [2025-08-19 12:00] - Successfully Submit Dummy Transaction via `curl`

- After correcting the account types and transaction type, successfully submitted a dummy transaction using `submit_dummy_transaction.sh`.
- Confirmed that `source_id` from a `revenue` account and `destination_id` from an `asset` account, with `TRANSACTION_TYPE="deposit"`, works correctly.

## [2025-08-19 12:15] - Start Integrating with Flutter App

- Goal: Create a Flutter screen to select source and destination accounts from Firefly III and submit a transaction.
- Checked `pubspec.yaml` and confirmed `http: ^1.5.0` is already included.
- Created `lib/models/firefly_account.dart`:
  - Defined a `FireflyAccount` model to represent account data from the API.
  - Includes `id`, `name`, and `type` properties.
  - Has a `fromJson` factory constructor for easy parsing.
- Created `lib/services/firefly_api_service.dart`:
  - Defined `FireflyApiService` class to encapsulate API calls.
  - Includes `fetchAccounts({String? type})` to get accounts, filtering by type if provided.
  - Includes `submitDummyTransaction` to send a transaction to the API.
  - Uses `Bearer` token authentication.
- Created `lib/screens/transaction_screen.dart`:
  - Defined `TransactionScreen` widget.
  - Fetches `revenue` and `asset` accounts on initialization.
  - Displays two dropdowns for selecting source (`revenue`) and destination (`asset`) accounts.
  - Includes buttons to reload accounts and submit a dummy transaction.
  - Shows loading indicators and status messages.

## [2025-08-19 12:30] - Improve Security & User Experience

- Recognized that hardcoding URL/token is insecure. Implemented a better approach.
- Created `lib/screens/config_screen.dart`:
  - New screen for users to input Firefly III URL and Personal Access Token.
  - Uses `TextField` for input with basic validation.
  - Stores credentials securely using `shared_preferences`.
- Modified `lib/services/firefly_api_service.dart`:
  - Removed hardcoded URL and token.
  - Updated `fetchAccounts` and `submitDummyTransaction` methods to accept `baseUrl` and `accessToken` as required parameters.
- Modified `lib/screens/transaction_screen.dart`:
  - Updated to load URL and token from `shared_preferences`.
  - Passes loaded credentials to `FireflyApiService` methods.
  - Adds a settings icon in the app bar to navigate to `ConfigScreen`.
  - Handles cases where credentials are missing or invalid.

## [2025-08-19 13:00] - Add Debug Logging for Account Loading

- Added extensive debug `print` statements to `FireflyApiService` and `TransactionScreen`.
- Purpose: To trace the flow of data loading, identify where the process might be failing, and verify if accounts are successfully fetched and parsed from the Firefly III API.
- This will help diagnose why the dropdowns for source and destination accounts might appear empty even after configuration is set.

## [2025-08-20 14:00] - Refactor main.dart and Correct Transaction Payload

- Corrected the payload in `lib/services/firefly_api_service.dart`'s `submitDummyTransaction` method. Ensured that `source_id` and `destination_id` are passed as strings to align with Firefly III API expectations.
- Refactored `lib/main.dart` to improve the initial application flow.
- Set `TransactionScreen` as the initial route (`/`).
- Added named routes for `TransactionScreen` (`/`), `ConfigScreen` (`/config`), and `ReceiptScreen` (`/receipt`) to create a clear and maintainable navigation structure.
- This change directs the user to the primary transaction interface on startup, facilitating immediate testing of the core functionality being developed.

## [2025-08-20 14:30] - Fix Compilation and Runtime Errors

- Resolved build errors caused by incorrect import paths and class names in `lib/screens/receipt_screen.dart` and `lib/screens/settings_screen.dart`.
- Corrected the import from `firefly_service.dart` to `firefly_api_service.dart`.
- Renamed all instances of `FireflyService` to the correct class name, `FireflyApiService`.
- Implemented the missing `testConnection` and `testAuthentication` methods in `lib/services/firefly_api_service.dart` to enable configuration testing.
- Updated `lib/screens/settings_screen.dart` to pass the required `baseUrl` and `accessToken` parameters to the new API service methods.
- The application is now in a runnable state, allowing for further testing of the Firefly III integration.

## [2025-08-20 15:00] - Redesign Receipt UI to Match Sample Image

- Redesigned the `ReceiptScreen` UI to match a more traditional receipt format similar to `sample-struk.jpg`.
- Updated the layout to have a receipt paper style with proper borders and styling.
- Improved the item list display with better alignment and formatting.
- Moved transaction settings to a separate section with better organization.
- Updated the PDF export service to match the new UI design.
- Fixed several syntax errors and code quality issues identified by the analyzer.
- The UI now has a more professional receipt appearance with proper spacing, dividers, and formatting.

## [2025-08-20 16:00] - Update Receipt UI with Courier Font and Fix Layout Issues

- Added `google_fonts` dependency to `pubspec.yaml` to use Courier Prime font for a more authentic receipt appearance.
- Updated `ReceiptScreen` to use a fixed-width layout that resembles a physical receipt.
- Added transaction details like cashier ID and transaction ID.
- Improved the overall styling with better spacing, dividers, and a thank you message.
- Fixed syntax errors in the `receipt_screen.dart` file that were preventing the app from building correctly.
- Successfully ran the app on a physical device and verified that the new UI is displayed correctly.
- Confirmed that the app can be navigated to the ReceiptScreen, though it currently defaults to TransactionScreen as the home route.

## [2025-08-20 17:00] - Fix PDF Export Path and Add PDF Opening Functionality

- Updated `PdfExportService` to use the application documents directory instead of temporary directory for saving PDF files.
- Added a function to open the generated PDF file using the `open_file` package.
- Modified `_printReceipt` function in `ReceiptScreen` to automatically open the generated PDF after creation.
- This ensures that users can easily access and view the generated receipt PDFs on their devices.

## [2025-08-20 18:00] - Implement Bluetooth Thermal Printer Functionality

- Integrated the `bluetooth_print` plugin to enable printing receipts on thermal printers.
- Added Bluetooth device scanning and connection functionality in `ReceiptScreen`.
- Implemented a function to format and print receipts to thermal printers using the ESC/POS protocol.
- Added UI elements to connect to Bluetooth printers and print receipts.
- The thermal printer functionality allows users to print receipts directly from the app to compatible Bluetooth thermal printers.

## [2025-08-20 19:00] - Fix UI Overflow and setState() After Dispose Errors

- Fixed UI overflow error in `ReceiptScreen` by properly sizing the action buttons using `Expanded` widgets.
- Resolved `setState() called after dispose` errors in `SettingsScreen` by adding `mounted` checks before calling `setState()`.
- These fixes improve the stability and user experience of the application.

## [2025-08-20 20:00] - Final Testing and Bug Fixes

- Successfully built and ran the application on a physical device.
- Verified that all core functionalities work as expected:
  - Connection to Firefly III API
  - Account fetching and selection
  - Transaction submission
  - PDF generation and opening
  - Bluetooth printer connection and printing
- Fixed remaining syntax errors in the codebase.
- The application is now fully functional and ready for use.

## [2025-08-21 14:00] - UI Refinement Round 1 & User Feedback

- Received user feedback on current UI state after implementing FAB for main actions.
- **Key Feedback Points Identified for Future Work:**
  - **Printer Setup Integration:** The UI for setting up the Bluetooth printer (`PrinterSetupScreen`) should be integrated into the main configuration/settings screen (`SettingsScreen`) for better user flow and consistency.
  - **UI Alignment Issue:** The visual effect of the torn receipt top (`ReceiptTearTop`) and bottom (`ReceiptTearBottom`) does not perfectly align or match the width/color of the main receipt container, creating a slight visual inconsistency.
  - **Store Info Update Lag:** When editing store information via the config dialog (triggered from `StoreInfoWidget`), the displayed information in the `StoreInfoWidget` itself does not update immediately after saving. A full screen reload or app restart is currently needed to see the changes.
  - **Item Addition UX:** The current flow for adding a new item (navigating to a new full screen `AddItemScreen`) could be improved. A floating, modal-like card overlay that appears on top of the current screen is suggested as a more seamless and modern user experience.

These points will be addressed in the next iteration of UI/UX improvements.

## [2025-08-21 15:00] - Implementing UI Refinements Based on Feedback

- **Addressed UI Alignment Issue:**
  - Modified `ReceiptTearTop` and `ReceiptTearBottom` widgets to have a fixed width of `320.0` to match the main receipt container.
  - Updated the background color of the tear effect containers to `Colors.grey[300]` to match the screen background, ensuring visual consistency.
- **Improved Store Info Update Mechanism:**
  - Modified `StoreInfoWidget` to load store information from `SharedPreferences` every time it's built (`build` method), instead of only in `initState()`. This ensures the widget displays the latest data after configuration changes without requiring a full screen reload.
- **Enhanced Item Addition UX:**
  - Changed the `_addItem()` and `_editItem()` methods in `ReceiptScreen` to use `showDialog` instead of `Navigator.push`.
  - This change makes `AddItemScreen` appear as a modal dialog overlay on top of the receipt screen, providing a smoother and less disruptive user experience when adding or editing items.
- **Integrated Printer Setup into Settings:**
  - Merged the functionality of `PrinterSetupScreen` into `SettingsScreen`.
  - Added Bluetooth printer setup UI elements (device scanning, connection status, device list) directly within the `SettingsScreen`.
  - `PrinterSetupScreen` is now obsolete and can be removed in a future cleanup.
- **Verified Changes:**
  - Built and ran the application on a physical device.
  - Confirmed that the UI elements are aligned correctly.
  - Tested that store information updates dynamically after saving in the config dialog.
  - Verified that the item addition/editing flow now uses a modal dialog.
  - Confirmed that printer setup is accessible and functional within the main settings screen.

## [2025-08-21 16:00] - Planning Next Set of Features and Improvements

Based on the latest user feedback, the following tasks have been identified for the next development cycle:

- **Clean Up FAB Actions:**
  - **Remove "Setup Printer" from FAB:** Since printer setup is now integrated into the main settings screen, the "Setup Printer" option will be removed from the Floating Action Button (FAB) menu in `ReceiptScreen`.

- **Enhance Firefly III Transaction Submission:**
  - **Auto-Generate PDF and Upload as Attachment:** Modify the `_sendToFirefly()` method to automatically generate a PDF of the receipt after a successful transaction submission and then upload this PDF as an attachment to the newly created transaction in Firefly III.
  
- **Improve Transaction Description Format:**
  - **Smart Transaction Title:** Update the transaction description logic in `_sendToFirefly()` to create a title based on the first 5 item descriptions.
  - Format: "Item1, Item2, Item3, Item4, Item5, dll" (if more than 5 items).
  - If 5 or fewer items, list them all separated by commas.

- **UI Polish:**
  - **Mirror Receipt Tear Effects:** Improve the visual design of `ReceiptTearTop` and `ReceiptTearBottom` to make them more aesthetically pleasing and symmetrical.
  
- **Customization Features:**
  - **Editable Disclaimer & Thank You Message:** Add functionality to allow users to customize the disclaimer text and the "thank you" message/pantun in the receipt via the settings screen.
  - **Add Store Logo Support:** Implement the ability for users to upload and display a store logo (SVG, PNG, etc.) in the `StoreInfoWidget`. This will involve adding image picking/uploading capabilities to the store info configuration and updating the widget to display the logo.

These tasks aim to further refine the application's functionality and user experience based on user input.

## [2025-08-21 17:00] - Implementation of Feature Enhancements

- **FAB Cleanup:**
  - Removed the "Setup Printer" option from the Floating Action Button (FAB) in `ReceiptScreen`.
  - Deleted the obsolete `_openPrinterSetup()` method.
  
- **Improved Transaction Description:**
  - Added `_generateTransactionDescription()` method to `ReceiptScreen` to create dynamic transaction titles based on item names.
  - Updated `_sendToFirefly()` to use the new description format: listing up to 5 items, with "dll" appended if there are more.

- **Enhanced Firefly API Service:**
  - Modified `submitDummyTransaction()` in `FireflyApiService` to return the transaction ID of the newly created transaction.
  - Added `uploadAttachment()` method to handle uploading files as attachments to Firefly III transactions.
  - Added helper methods `_parseAttachmentId()` and `_linkAttachmentToTransaction()` for attachment handling.
  
- **UI Improvements for Receipt Tear Effects:**
  - Updated `ReceiptTearTop` and `ReceiptTearBottom` widgets to create more visually appealing and symmetrical tear effects using randomized peaks and valleys.
  
- **Customizable Receipt Text:**
  - Made `StoreDisclaimer` and `ThankYouPantun` widgets stateful to load their content from `SharedPreferences`.
  - Created `CustomTextConfigDialog` widget to allow users to edit disclaimer, thank you, and pantun texts.
  - Added an "Edit Teks Kustom" button in `SettingsScreen` to access the new dialog.
  
- **Store Logo Support:**
  - Added `image_picker` package dependency to `pubspec.yaml`.
  - Modified `StoreInfoWidget` to display a store logo if one is set.
  - Updated `StoreInfoConfigDialog` to include image picking functionality, allowing users to select a logo from their device's gallery.
  - Logo path is stored in `SharedPreferences` and loaded when the widget is built.

- **Preparation for PDF Attachment:**
  - Updated `_sendToFirefly()` in `ReceiptScreen` to generate a PDF after successful transaction submission (PDF generation logic already existed).
  - Added placeholder comment for future implementation of PDF upload to Firefly III.

## [2025-08-21 18:00] - Code Fixes and Improvements

- **Fixed Critical Compilation Error:**
  - Corrected type mismatch in `TransactionScreen` where `FireflyApiService.submitDummyTransaction()` returned `Future<String?>` but was being assigned to a `bool` variable.
  - Fixed the assignment to properly handle the returned transaction ID.

- **Removed Unused Code and Imports:**
  - Removed unused imports in `ReceiptScreen` including `google_fonts`, `settings_screen`, and `firefly_transaction_info`.
  - Removed unused methods `_checkBluetoothStatus`, `_scanBluetoothDevices`, `_selectDate`, `_onSourceAccountChanged`, and `_onDestinationAccountChanged`.
  - Removed unused `_saveBluetoothDevice` method and `_bluetoothScanning` field.
  - Fixed duplicate imports in `store_info_widget.dart`.
  - Removed unused `image_picker` import from `store_info_widget.dart`.

- **Addressed Code Quality Issues:**
  - Fixed unused variable `courierPrime` in `receipt_widgets.dart`.
  - Removed unused import in `cashier_home.dart`.

- **Current Status:**
  - The application compiles successfully after fixes.
  - There are still several analyzer warnings (mostly related to print statements and performance suggestions) that could be addressed in future iterations.
  - The core functionality is preserved and working.

## [2025-08-21 20:00] - Enhanced Receipt Tear Effect Visualization

- **Improved Receipt Tear Effects:**
  - Refined the visual design of `ReceiptTearTop` and `ReceiptTearBottom` widgets to create more realistic torn paper effects.
  - Corrected the direction of tear patterns so they properly face outward from the receipt (upward for top tear, downward for bottom tear).
  
- **Optimized Layout and Positioning:**
  - Centered the receipt layout on the screen using `Center` widget for better visual balance.
  - Added appropriate spacing around tear effects to ensure they remain visible even when the receipt content is scrolled.
  - Implemented proper background coloring (`Colors.grey[300]`) for tear effect containers to match the screen background, ensuring visual consistency.
  
- **Enhanced Scrolling Experience:**
  - Ensured tear effects remain visible during scrolling by providing adequate clearance and proper positioning within the scrollable area.
  - Added sufficient padding (15px top/bottom, 1px between tear effect and content) to make tear patterns clearly visible while maintaining visual connection to the receipt content.
  
- **Populated Sample Data:**
  - Added more sample items to the receipt to ensure the content exceeds screen height, demonstrating the scrolling functionality with tear effects.
  
- **Verified Improvements:**
  - Built and ran the application on a physical device.
  - Confirmed that tear effects are clearly visible and properly positioned.
  - Tested scrolling behavior to ensure tear effects remain visible and connected to the receipt content.
  - Verified visual consistency across different screen sizes and orientations.

## [2025-08-21 21:00] - Implemented Editable Store Disclaimer and Thank You Messages

- **Added Tap-to-Edit Functionality:**
  - Enhanced `StoreDisclaimer` and `ThankYouPantun` widgets with `onTap` callbacks to enable editing when tapped.
  - Modified both widgets to use `GestureDetector` to capture tap events and trigger the custom text configuration dialog.
  
- **Improved User Experience:**
  - Users can now directly tap on the disclaimer or thank you message sections in the receipt to edit their content.
  - Added visual feedback when these sections are tapped, providing an intuitive way to customize the receipt text.
  
- **Integrated Custom Text Configuration:**
  - Reused the existing `CustomTextConfigDialog` for editing disclaimer and thank you messages.
  - Added `_openCustomTextConfig` method to `ReceiptScreen` to handle the dialog display and result processing.
  - Ensured that changes to disclaimer and thank you text are immediately reflected in the receipt after saving.
  
- **Updated Configuration Screen:**
  - Added an "Edit Teks Kustom" button in `ConfigScreen` to provide an alternative way to access the text customization dialog.
  - Enhanced the configuration flow to make it easier for users to customize their receipt content.
  
- **Verified Implementation:**
  - Built and ran the application on a physical device.
  - Confirmed that tapping on disclaimer and thank you sections opens the text configuration dialog.
  - Tested saving custom text and verified that changes are properly persisted and displayed.
  - Ensured that both direct tapping on receipt sections and accessing through settings work correctly.

## [2025-08-21 22:00] - UI Improvements and Receipt Formatting Enhancements

- **Improved Add Item Dialog:**
  - Replaced the full-screen `AddItemScreen` with a modal `AlertDialog` for a more streamlined user experience.
  - Eliminated page navigation when adding or editing items, keeping users in the context of the receipt.
  - Maintained all functionality while providing a more intuitive interface.
  
- **Enhanced Account Settings Display:**
  - Removed the "Pengaturan Transaksi" label for a cleaner look.
  - Changed "Sumber" to "Dari" and "Tujuan" to "Ke" for clearer transaction flow indication.
  - Improved the overall visual hierarchy of the transaction settings section.
  
- **Added Transaction Summary:**
  - Implemented a total price display below the "Tambah Item" button.
  - Added a dotted line separator below the total to match traditional receipt formatting.
  - Ensured the total is properly formatted with Indonesian Rupiah currency symbol and thousand separators.
  
- **Added Column Headers:**
  - Inserted column headers ("ITEM", "QTY", "HARGA", "TOTAL") above the item list for better readability.
  - Aligned column headers with item data columns for visual consistency.
  
- **Implemented Currency Formatting:**
  - Added `_formatRupiah` method to properly format monetary values with "Rp" prefix and thousand separators.
  - Applied currency formatting to all price displays in both the item list and total summary.
  - Used the `intl` package for proper localization of number formatting.
  
- **Optimized Layout and Spacing:**
  - Increased the receipt width from 320 to 360 pixels to accommodate better column alignment and prevent text overlap.
  - Adjusted column flex values to ensure consistent alignment between headers and item data.
  - Updated `ReceiptTearTop` and `ReceiptTearBottom` widgets to match the new receipt width.
  
- **Verified Improvements:**
  - Built and ran the application on a physical device.
  - Confirmed that all UI elements are properly aligned and formatted.
  - Tested the add/edit item flow to ensure it works smoothly with the new dialog interface.
  - Verified that currency formatting is displayed correctly for various price points.
  - Ensured that the receipt layout remains visually appealing and readable on different screen sizes.

## [2025-08-21 23:00] - Refinement of Item Interaction and Layout

- **Implemented Dismissible for Item Actions:**
  - Replaced permanent edit/delete buttons in `ReceiptItemWidget` with swipe gestures using `Dismissible`.
  - Configured swipe right (`startToEnd`) to delete an item.
  - Configured swipe left (`endToStart`) to edit an item.
  - Added visual feedback with red background for delete and blue background for edit actions.
  
- **Improved Item Layout and Readability:**
  - Adjusted column flex values in `ReceiptItemWidget` to better distribute space.
  - Increased the flex value for the item description column to provide more room.
  - Added `TextOverflow.ellipsis` to item descriptions to prevent layout overflow.
  - Removed permanent action buttons, creating a cleaner and less cluttered item list.
  
- **Investigated Item Disappearance Issue on Edit Cancel:**
  - **Initial Issue:** User reported that items were disappearing when editing was canceled via swipe.
  - **Initial Investigation & Findings:** Added detailed logging to `_editItem` and `AddItemScreen`. Logs confirmed that when "Batal" (Cancel) is pressed in the edit dialog, `null` is returned and the item list is not modified by the `_editItem` function itself.
  - **Revised Understanding:** Further testing revealed that the item *does* visually disappear from the list after a swipe-left-to-edit-cancel sequence, even though the underlying list data is not modified. This suggests a UI rendering problem related to the `Dismissible` widget's state after being canceled.
  - **Hypothesis:** The `Dismissible` widget might not be properly resetting its state or being disposed of correctly after the edit dialog is canceled, leading to an inconsistent UI state where the item is not rendered even though it exists in the `items` list.
  - **Planned Solution:** Investigate forcing a full rebuild/refresh of the item list UI after a dismiss action (both edit and delete) to ensure the `Dismissible` widgets and the list rendering are in sync with the `items` data source. This might involve calling `setState` at a higher level or using a different keying strategy for the `Dismissible` widgets.
  
- **Identified Minor UI Warning:**
  - **Warning:** Encountered a Flutter assertion error: `A dismissed Dismissible widget is still part of the tree.`.
  - **Analysis:** This is a known issue related to how `Dismissible` widgets interact with list rebuilds in Flutter. It occurs when the list is updated after a dismiss action, but the widget tree is not immediately consistent.
  - **Impact:** This does not crash the app or affect functionality but is a cosmetic issue that can be addressed in future refinements.
  - **Plan:** Monitor this warning. If it becomes problematic, consider more advanced state management solutions or key-based widget identification for the list.

## [2025-08-22 09:00] - Solved Item Disappearance Bug and Refactored Item Interaction

- **Fixed `Dismissible` Item Disappearance Bug:**
  - **Root Cause:** The `Dismissible` widget was causing UI inconsistencies when an edit action was canceled. The widget was being dismissed visually even though the underlying data remained unchanged, leading to the item disappearing from the list.
  - **Solution:** Replaced the `Dismissible` widget with a more direct interaction model. The swipe-to-edit/delete functionality has been removed in favor of a `GestureDetector` that wraps the `ReceiptItemWidget`. A simple `onTap` now triggers the `_editItem` dialog, and a new `onLongPress` triggers a confirmation dialog for deletion.
  - **Benefits:** This approach is more stable, avoids the complexities and bugs associated with the `Dismissible` widget in this context, and provides a clear, explicit user action for deletion (long press) to prevent accidental removals.

- **Improved `ReceiptItemWidget` Interaction:**
  - Removed the `onEdit` and `onDelete` callback parameters as they are no longer needed.
  - The widget is now simpler and only responsible for displaying item data.

- **Updated `ReceiptScreen` Logic:**
  - Modified the `ListView` builder to wrap each `ReceiptItemWidget` in a `GestureDetector`.
  - Implemented `onTap: () => _editItem(index)` for editing.
  - Implemented `onLongPress: () => _confirmRemoveItem(index)` for deletion, which shows an `AlertDialog` to confirm the action before removing the item.

- **Verified Fix:**
  - Built and ran the application.
  - Confirmed that tapping an item opens the edit dialog.
  - Confirmed that canceling the edit dialog no longer causes the item to disappear.
  - Confirmed that long-pressing an item brings up a confirmation dialog and that deletion works as expected.

## [2025-08-22 09:15] - Implemented and Verified PDF Attachment Upload to Firefly III

- **Refactored `FireflyApiService` for Attachment Upload:**
  - **Problem:** The previous implementation for uploading attachments was incorrect. It involved two separate API calls: one to upload the file and another to link it to a transaction. The Firefly III API expects these to be a single action.
  - **Solution:** Modified the `uploadAttachment` method to send a single `POST` request to the `/api/v1/attachments` endpoint. This single request now includes the file itself along with the `attachable_type` ('TransactionJournal') and `attachable_id` (the transaction ID) as multipart form data.
  - **Cleanup:** Removed the now-redundant helper methods `_parseAttachmentId` and `_linkAttachmentToTransaction`, simplifying the service class.

- **Verified End-to-End Flow:**
  - Triggered the `_sendToFirefly` function in `ReceiptScreen`.
  - **Step 1: Transaction Submission:** Confirmed that the transaction is successfully created in Firefly III.
 - **Step 2: PDF Generation:** Confirmed that the PDF receipt is generated locally on the device.
  - **Step 3: PDF Upload:** Confirmed that the `uploadAttachment` service method is called with the correct transaction ID and PDF data.
  - **Step 4: Verification in Firefly III:** Manually checked the Firefly III instance and verified that the newly created transaction now has the correct PDF receipt attached to it.

- **Current Status:** The core feature of submitting a transaction and attaching the corresponding PDF receipt is now fully implemented and working correctly.

## [2025-09-18 11:39] - Update Item Quantity to Support Double Values

- **Feature Enhancement:** Modified the `ReceiptItem` model to support double values for quantities instead of only integers.
- **Changes Made:**
  - Updated `quantity` property in `ReceiptItem` model from `int` to `double`
  - Modified the quantity input validation in `AddItemScreen` to accept decimal values using `double.tryParse()` instead of `int.tryParse()`
  - Updated the quantity display and calculation logic to handle decimal quantities properly
- **Impact:** This allows for more flexible item management, supporting scenarios like 0.5 kg of vegetables, 1.25 liters of liquid, etc.
- **Co-authored-by:** Qwen-Coder <qwen-coder@alibabacloud.com>

## [2025-11-17 11:57] - Remove Default Account Mapping Feature and Implement Offline-First Account Mirroring

- **Major Feature Removal:** Completely removed the default account mapping system that was causing confusion and reliability issues
- **Offline-First Implementation:** Implemented robust offline account mirroring system that maintains local copies of all FireFly III accounts
- **Key Changes:**
  - **AccountCacheService:** Removed all default account mapping functions (saveDefaultAccount, getDefaultAccount, etc.)
  - **ReceiptProvider:** Updated to not rely on default account mapping, using direct account selection instead
  - **TransactionScreen:** Removed default account mapping UI elements and logic
  - **ConfigScreen:** Removed default account mapping display and management controls
  - **AccountDialogService:** Updated account selection dialogs to work without default mappings
  - **ReceiptService:** Removed default account mapping related functions
  - **LocalReceiptService:** Updated to not depend on default account mappings
- **New Features:**
  - Account mirroring system that stores all accounts locally for offline access
  - Fallback mechanism: server accounts > mirrored accounts > empty list
  - Automatic account sync when connection is available
  - Manual sync button in config screen
- **Benefits:**
  - Simplified architecture without complex default mapping logic
  - Better offline reliability - app works completely without server connection
  - Faster startup times using local account cache
  - More predictable account selection behavior
  - Reduced confusion about which accounts are being used
- **Testing Results:** Application successfully runs in offline mode with mirrored accounts, maintains functionality when server is unavailable

## [2025-11-08 12:15] - Implement Receipt Caching and Offline Submission

- **New Feature:** Added offline capability to cache receipts locally and submit them when the FireFly III server becomes available.
- **Key Changes:**
  - Enhanced `LocalReceiptService` to store receipts with submission status tracking
 - Added `fireflyTransactionId` and `fireflyTransactionUrl` properties to `LocalReceipt` model to store transaction references
  - Implemented automatic retry mechanism for failed submissions when network connectivity is restored
 - Added server availability checking before attempting to submit transactions
  - Modified `ReceiptService` to handle both online and offline submission scenarios
- **Benefits:** Users can continue working even when the FireFly III server is temporarily unavailable, with transactions being queued and submitted automatically when connectivity is restored.

## [2025-11-08 13:38] - Add Swipe-to-Delete and WebView Transaction Features

- **Enhanced Local Receipts Screen:**
  - **Swipe-to-Delete:** Implemented `Dismissible` widget in `LocalReceiptsScreen` to allow users to swipe right-to-left to delete receipts
  - **Visual Feedback:** Added red background with delete icon during swipe action for clear user feedback
  - **Confirmation:** Integrated with existing delete confirmation logic for safety

- **FireFly III Transaction WebView Integration:**
  - **New Model Property:** Added `fireflyTransactionUrl` to `LocalReceipt` model to store the URL of the transaction in FireFly III
  - **WebView Screen:** Created `WebViewScreen` widget to display FireFly III transactions within the app
  - **Navigation:** Added tap functionality on receipt items in `LocalReceiptsScreen` to open the corresponding FireFly III transaction in WebView
  - **URL Construction:** Implemented proper URL generation for FireFly III transaction viewing: `'$baseUrl/transactions/show/$transactionId'`

- **Improved Currency Formatting:**
  - Enhanced currency formatting in `LocalReceiptsScreen` to properly handle Rupiah formatting without removing decimal places when necessary
  - Maintained `.00` suffix only when required for proper currency display

- **Enhanced ReceiptService:**
  - Updated `submitReceiptToFirefly` method to save the transaction ID and URL back to the local receipt after successful submission
  - Added proper error handling and transaction reference updates during the submission process

## [2026-01-11 11:47] - Major Refactor of Printing Service Architecture

- **Identified Performance Issues:** The previous implementation had several architectural problems:
  - **Monolithic Functions:** `generateEscPosBytes()` function was extremely long (300+ lines) and handled too many responsibilities
  - **Code Duplication:** Multiple printing approaches existed simultaneously (`PrintService` and `EscPosPrintService`)
  - **Inefficient Preferences Reading:** Shared preferences were read multiple times in a single operation
  - **Poor Error Handling:** Inconsistent error handling across the printing workflow
  - **Violation of Single Responsibility Principle:** Functions were doing too many things at once

- **Complete Refactor of EscPosPrintService:**
  - **Modular Design:** Broke down the monolithic `generateEscPosBytes()` into focused, single-responsibility functions:
    - `_addStoreLogo()` - handles logo display
    - `_addStoreHeader()` - handles store header information
    - `_addItemList()` - handles item list rendering
    - `_addTotals()` - handles total calculations and payment info
    - `_addFooter()` - handles disclaimer and thank you messages
  - **Data Classes:** Introduced `StoreConfig` and `PaymentInfo` classes for better data organization
  - **Configuration Management:** Created `PrintConfig` class for centralized printer configuration
  - **Error Handling:** Implemented `PrintErrorHandler` for consistent error handling

- **Standardized Printing Approach:**
  - **Removed Redundant Service:** Deleted `lib/services/print_service.dart` which duplicated functionality
  - **Unified Approach:** All printing now uses the standardized `EscPosPrintService` with `flutter_esc_pos_utils`
  - **Consistent Parameter Usage:** Replaced individual `paymentAmount` and `isTip` parameters with `PaymentInfo` object

- **Performance Optimizations:**
  - **Batch Preferences Reading:** `StoreConfig.fromSharedPreferences()` now reads all store-related preferences in one batch operation
  - **Efficient Configuration:** `PrintConfig.loadPrinterConfig()` loads all printer settings at once
  - **Reduced Disk Reads:** Minimized repeated file system access for better performance

- **Enhanced Error Handling:**
  - **Comprehensive Catch Blocks:** Added proper error handling for all printing operations
  - **Context-Aware Logging:** Implemented detailed error logging with context information
  - **Graceful Degradation:** Added fallback mechanisms for when certain features fail

- **Testing and Verification:**
  - **Unit Tests:** Created comprehensive unit tests in `test/print_service_unit_test.dart`
  - **Function Verification:** All core functions tested and verified working (6/6 tests passed)
  - **Integration Testing:** Verified the complete printing workflow from receipt generation to thermal printer output

- **Benefits Achieved:**
  - **Maintainability:** Code is now modular and easier to modify
  - **Performance:** Reduced redundant operations and optimized preferences reading
  - **Reliability:** Consistent error handling reduces crashes
  - **Scalability:** Modular design allows for easy feature additions
  - **Consistency:** Single printing approach eliminates confusion
  - **Developer Experience:** Clearer code structure and better documentation