Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(mobile): view and edit transaction splits (#4427)

Bhargav Mehta2ebebe5d1a5f
diff --git a/mobile/docs/OFFLINE_FEATURES.md b/mobile/docs/OFFLINE_FEATURES.md
index 2ab80a79c0..5ee07af53d 100644
--- a/mobile/docs/OFFLINE_FEATURES.md
+++ b/mobile/docs/OFFLINE_FEATURES.md
@@ -319,6 +319,38 @@ The app automatically syncs in these scenarios:
- **Cache Invalidation**: Account cache is refreshed on each sync to ensure accurate balances
- **Memory Usage**: Only active transactions are kept in memory; database queries are paginated
+## Online-only Actions
+
+### Transaction Splits
+
+Splitting a transaction, editing a split and unsplitting call
+`/api/v1/transactions/:id/split` directly and are **not** queued offline: the
+offline queue only replays creates and deletes. While offline, the split section
+on the transaction screen is read-only (cached splits stay visible) and the
+split editor cannot save.
+
+After a split write, children the server destroyed are removed from the local
+cache and the account's transactions are re-fetched, because an account-scoped
+sync only upserts. Those ids are dropped again after every later sync in the
+session (an overlapping sync can still return them), refreshes run one at a
+time, and an account whose refresh could not sync is synced on its next load.
+The transactions index flags split parents (`split_parent`) and sends the
+exact stored amount (`amount_decimal`), the `kind` and the `excluded` flag;
+all four are cached with the transaction (database version 4). Flagged parents
+are shown as split parents straight away, and their splits are looked up in the
+background (one request at a time, at most 20 per list load) so their children
+can be grouped under them. The calendar leaves split parents out of its daily
+totals, and a new split starts from the exact amount (so 100.1250 USD splits to
+exactly 100.1250). Servers without these fields fall back to the splits the
+app has loaded and to the display amount.
+
+Deleting from the transactions list (swipe or bulk) refuses flagged split
+parents and checks every other row's split membership with the server first,
+refusing split parents and children ("Unsplit this transaction before deleting
+it"); if that check fails while online, the delete is refused too. Offline,
+flagged parents and splits already loaded on the device are refused, so
+offline deletion keeps working.
+
## Future Enhancements
Potential improvements for future versions:
@@ -327,9 +359,8 @@ Potential improvements for future versions:
2. **Selective Sync**: Sync only specific accounts or date ranges
3. **Background Sync**: Use platform background tasks for periodic syncing
4. **Offline Editing**: Support editing transactions offline
-5. **Offline Deletion**: Support deleting transactions offline with sync
-6. **Export Offline Data**: Export local database for backup
-7. **Data Compression**: Compress large sync payloads for better performance
+5. **Export Offline Data**: Export local database for backup
+6. **Data Compression**: Compress large sync payloads for better performance
## Troubleshooting
diff --git a/mobile/docs/TECHNICAL_GUIDE.md b/mobile/docs/TECHNICAL_GUIDE.md
index 060960c5e3..f5ec2cb137 100644
--- a/mobile/docs/TECHNICAL_GUIDE.md
+++ b/mobile/docs/TECHNICAL_GUIDE.md
@@ -259,6 +259,12 @@ The app interacts with the backend through the following API endpoints:
### Accounts
- `GET /api/v1/accounts` - Get account list (supports pagination)
+### Transaction Splits
+- `GET /api/v1/transactions/:id/split` - Get a split (404 "Transaction is not split" when not split, told apart from a missing transaction's 404; a child id resolves to its parent)
+- `POST /api/v1/transactions/:id/split` - Split a transaction
+- `PATCH /api/v1/transactions/:id/split` - Replace every child of a split
+- `DELETE /api/v1/transactions/:id/split` - Unsplit
+
### Health Check
- `GET /sessions/new` - Verify backend service availability
diff --git a/mobile/lib/l10n/app_en.arb b/mobile/lib/l10n/app_en.arb
index 29cae5ca5e..e7dd7a53c0 100644
--- a/mobile/lib/l10n/app_en.arb
+++ b/mobile/lib/l10n/app_en.arb
@@ -1192,5 +1192,143 @@
"@cashFlowTransactionsEmpty": { "description": "Empty state of the category transactions screen." },
"cashFlowTransactionsLoadFailed": "Couldn't load transactions",
- "@cashFlowTransactionsLoadFailed": { "description": "Error state of the category transactions screen." }
+ "@cashFlowTransactionsLoadFailed": { "description": "Error state of the category transactions screen." },
+
+"splitBadge": "Split",
+ "@splitBadge": { "description": "Pill on a split parent in the transaction list." },
+
+"splitSectionTitle": "Split entries",
+ "@splitSectionTitle": { "description": "Title of the split section on a split parent's detail screen." },
+
+"splitSectionDescription": "This transaction has been split into the following entries.",
+ "@splitSectionDescription": { "description": "Description above the list of split children." },
+
+"splitChildTitle": "Part of split",
+ "@splitChildTitle": { "description": "Title of the split section on a split child's detail screen." },
+
+"splitChildDescription": "This entry is part of a split transaction. Edit the split to change it.",
+ "@splitChildDescription": { "description": "Description shown on a split child's detail screen." },
+
+"splitChildEditLocked": "Split entries can't be edited directly. Use Edit split below.",
+ "@splitChildEditLocked": { "description": "Notice on the edit screen of a split child, whose fields are read-only." },
+
+"splitStatusUnknownLocked": "Checking whether this transaction is split. The fields stay locked until that finishes.",
+ "@splitStatusUnknownLocked": { "description": "Notice on the edit screen while the split lookup is pending or has failed; the form is read-only." },
+
+"splitUncategorized": "(uncategorized)",
+ "@splitUncategorized": { "description": "Category label for a split entry without a category." },
+
+"splitTransactionButton": "Split transaction",
+ "@splitTransactionButton": { "description": "Button and section title that opens the split editor for an unsplit transaction." },
+
+"splitTransactionDescription": "Split this transaction into multiple entries with different categories and amounts.",
+ "@splitTransactionDescription": { "description": "Description of the split action on the detail screen." },
+
+"splitEditButton": "Edit split",
+ "@splitEditButton": { "description": "Button that opens the split editor for an existing split." },
+
+"splitUnsplitButton": "Unsplit",
+ "@splitUnsplitButton": { "description": "Button that removes a split and restores the original transaction." },
+
+"splitUnsplitTitle": "Unsplit transaction",
+ "@splitUnsplitTitle": { "description": "Title of the unsplit confirmation dialog." },
+
+"splitUnsplitConfirm": "This will remove all split entries and restore the original transaction.",
+ "@splitUnsplitConfirm": { "description": "Body of the unsplit confirmation dialog." },
+
+"splitUnsplitSuccess": "Transaction unsplit successfully",
+ "@splitUnsplitSuccess": { "description": "Snackbar after a split is removed." },
+
+"splitUnsplitFailed": "Failed to unsplit transaction",
+ "@splitUnsplitFailed": { "description": "Fallback snackbar when removing a split fails." },
+
+"splitOfflineNotice": "Connect to the internet to load or edit split details.",
+ "@splitOfflineNotice": { "description": "Shown on the detail screen while offline, since splits need the server." },
+
+"splitLoadFailed": "Couldn't load split details.",
+ "@splitLoadFailed": { "description": "Shown when the split details request fails." },
+
+"splitEditorNewTitle": "Split transaction",
+ "@splitEditorNewTitle": { "description": "App bar title of the split editor when creating a split." },
+
+"splitEditorEditTitle": "Edit split",
+ "@splitEditorEditTitle": { "description": "App bar title of the split editor when editing a split." },
+
+"splitEditorOriginalAmount": "Original amount",
+ "@splitEditorOriginalAmount": { "description": "Label for the parent transaction amount in the split editor." },
+
+"splitEditorRowLabel": "Split #{number}",
+ "@splitEditorRowLabel": {
+ "description": "Heading of one row in the split editor.",
+ "placeholders": { "number": { "type": "int" } }
+ },
+
+"splitEditorNameLabel": "Name",
+ "@splitEditorNameLabel": { "description": "Label for a split row's name field." },
+
+"splitEditorNamePlaceholder": "Split name",
+ "@splitEditorNamePlaceholder": { "description": "Placeholder for a split row's name field." },
+
+"splitEditorNameRequired": "Name is required",
+ "@splitEditorNameRequired": { "description": "Validation error for an empty split row name." },
+
+"splitEditorAmountLabel": "Amount",
+ "@splitEditorAmountLabel": { "description": "Label for a split row's amount field." },
+
+"splitEditorAmountHelper": "Enter amounts in the same direction as the original transaction. Use a minus sign for a part that goes the other way.",
+ "@splitEditorAmountHelper": { "description": "Helper text explaining the sign convention for split amounts." },
+
+"splitEditorAmountRequired": "Amount is required",
+ "@splitEditorAmountRequired": { "description": "Validation error for an empty split amount." },
+
+"splitEditorAmountInvalid": "Enter a valid amount",
+ "@splitEditorAmountInvalid": { "description": "Validation error for an unparseable split amount." },
+
+"splitEditorAmountZero": "Amount can't be zero",
+ "@splitEditorAmountZero": { "description": "Validation error for a zero split amount." },
+
+"splitEditorAmountTooPrecise": "Use at most {decimals} decimal places",
+ "@splitEditorAmountTooPrecise": {
+ "description": "Validation error when a split amount has more decimals than the currency allows.",
+ "placeholders": { "decimals": { "type": "int" } }
+ },
+
+"splitEditorCategoryLabel": "Category",
+ "@splitEditorCategoryLabel": { "description": "Label for a split row's category picker." },
+
+"splitEditorAddRow": "Add split",
+ "@splitEditorAddRow": { "description": "Button that adds a row to the split editor." },
+
+"splitEditorRemoveRow": "Remove split",
+ "@splitEditorRemoveRow": { "description": "Tooltip for the button that removes a split row." },
+
+"splitEditorRemaining": "Remaining",
+ "@splitEditorRemaining": { "description": "Label of the remaining-to-allocate indicator." },
+
+"splitEditorAmountsMustMatch": "Split amounts must equal the original transaction amount.",
+ "@splitEditorAmountsMustMatch": { "description": "Shown while the split rows do not add up to the original amount." },
+
+"splitEditorSubmitNew": "Split transaction",
+ "@splitEditorSubmitNew": { "description": "Save button label when creating a split." },
+
+"splitEditorSubmitEdit": "Update split",
+ "@splitEditorSubmitEdit": { "description": "Save button label when editing a split." },
+
+"splitEditorSaved": "Transaction split successfully",
+ "@splitEditorSaved": { "description": "Snackbar after a split is created." },
+
+"splitEditorUpdated": "Split updated successfully",
+ "@splitEditorUpdated": { "description": "Snackbar after a split is updated." },
+
+"splitEditorSaveFailed": "Failed to save split",
+ "@splitEditorSaveFailed": { "description": "Fallback snackbar when saving a split fails." },
+
+"splitEditorOffline": "You're offline. Splits can only be saved while connected.",
+ "@splitEditorOffline": { "description": "Shown in the split editor while offline." },
+
+"transactionsListSplitDeleteBlocked": "Unsplit this transaction before deleting it.",
+ "@transactionsListSplitDeleteBlocked": { "description": "Snackbar when deleting a split parent or child directly." },
+
+"transactionsListSplitStatusUnknown": "Couldn't check whether this transaction is split. Please try again.",
+ "@transactionsListSplitStatusUnknown": { "description": "Snackbar when a delete is blocked because the split lookup failed while online." }
}
diff --git a/mobile/lib/l10n/app_localizations.dart b/mobile/lib/l10n/app_localizations.dart
index ca7453cf46..85507dbb9e 100644
--- a/mobile/lib/l10n/app_localizations.dart
+++ b/mobile/lib/l10n/app_localizations.dart
@@ -2281,6 +2281,270 @@ abstract class AppLocalizations {
/// In en, this message translates to:
/// **'Couldn\'t load transactions'**
String get cashFlowTransactionsLoadFailed;
+
+ /// Pill on a split parent in the transaction list.
+ ///
+ /// In en, this message translates to:
+ /// **'Split'**
+ String get splitBadge;
+
+ /// Title of the split section on a split parent's detail screen.
+ ///
+ /// In en, this message translates to:
+ /// **'Split entries'**
+ String get splitSectionTitle;
+
+ /// Description above the list of split children.
+ ///
+ /// In en, this message translates to:
+ /// **'This transaction has been split into the following entries.'**
+ String get splitSectionDescription;
+
+ /// Title of the split section on a split child's detail screen.
+ ///
+ /// In en, this message translates to:
+ /// **'Part of split'**
+ String get splitChildTitle;
+
+ /// Description shown on a split child's detail screen.
+ ///
+ /// In en, this message translates to:
+ /// **'This entry is part of a split transaction. Edit the split to change it.'**
+ String get splitChildDescription;
+
+ /// Notice on the edit screen of a split child, whose fields are read-only.
+ ///
+ /// In en, this message translates to:
+ /// **'Split entries can\'t be edited directly. Use Edit split below.'**
+ String get splitChildEditLocked;
+
+ /// Notice on the edit screen while the split lookup is pending or has failed; the form is read-only.
+ ///
+ /// In en, this message translates to:
+ /// **'Checking whether this transaction is split. The fields stay locked until that finishes.'**
+ String get splitStatusUnknownLocked;
+
+ /// Category label for a split entry without a category.
+ ///
+ /// In en, this message translates to:
+ /// **'(uncategorized)'**
+ String get splitUncategorized;
+
+ /// Button and section title that opens the split editor for an unsplit transaction.
+ ///
+ /// In en, this message translates to:
+ /// **'Split transaction'**
+ String get splitTransactionButton;
+
+ /// Description of the split action on the detail screen.
+ ///
+ /// In en, this message translates to:
+ /// **'Split this transaction into multiple entries with different categories and amounts.'**
+ String get splitTransactionDescription;
+
+ /// Button that opens the split editor for an existing split.
+ ///
+ /// In en, this message translates to:
+ /// **'Edit split'**
+ String get splitEditButton;
+
+ /// Button that removes a split and restores the original transaction.
+ ///
+ /// In en, this message translates to:
+ /// **'Unsplit'**
+ String get splitUnsplitButton;
+
+ /// Title of the unsplit confirmation dialog.
+ ///
+ /// In en, this message translates to:
+ /// **'Unsplit transaction'**
+ String get splitUnsplitTitle;
+
+ /// Body of the unsplit confirmation dialog.
+ ///
+ /// In en, this message translates to:
+ /// **'This will remove all split entries and restore the original transaction.'**
+ String get splitUnsplitConfirm;
+
+ /// Snackbar after a split is removed.
+ ///
+ /// In en, this message translates to:
+ /// **'Transaction unsplit successfully'**
+ String get splitUnsplitSuccess;
+
+ /// Fallback snackbar when removing a split fails.
+ ///
+ /// In en, this message translates to:
+ /// **'Failed to unsplit transaction'**
+ String get splitUnsplitFailed;
+
+ /// Shown on the detail screen while offline, since splits need the server.
+ ///
+ /// In en, this message translates to:
+ /// **'Connect to the internet to load or edit split details.'**
+ String get splitOfflineNotice;
+
+ /// Shown when the split details request fails.
+ ///
+ /// In en, this message translates to:
+ /// **'Couldn\'t load split details.'**
+ String get splitLoadFailed;
+
+ /// App bar title of the split editor when creating a split.
+ ///
+ /// In en, this message translates to:
+ /// **'Split transaction'**
+ String get splitEditorNewTitle;
+
+ /// App bar title of the split editor when editing a split.
+ ///
+ /// In en, this message translates to:
+ /// **'Edit split'**
+ String get splitEditorEditTitle;
+
+ /// Label for the parent transaction amount in the split editor.
+ ///
+ /// In en, this message translates to:
+ /// **'Original amount'**
+ String get splitEditorOriginalAmount;
+
+ /// Heading of one row in the split editor.
+ ///
+ /// In en, this message translates to:
+ /// **'Split #{number}'**
+ String splitEditorRowLabel(int number);
+
+ /// Label for a split row's name field.
+ ///
+ /// In en, this message translates to:
+ /// **'Name'**
+ String get splitEditorNameLabel;
+
+ /// Placeholder for a split row's name field.
+ ///
+ /// In en, this message translates to:
+ /// **'Split name'**
+ String get splitEditorNamePlaceholder;
+
+ /// Validation error for an empty split row name.
+ ///
+ /// In en, this message translates to:
+ /// **'Name is required'**
+ String get splitEditorNameRequired;
+
+ /// Label for a split row's amount field.
+ ///
+ /// In en, this message translates to:
+ /// **'Amount'**
+ String get splitEditorAmountLabel;
+
+ /// Helper text explaining the sign convention for split amounts.
+ ///
+ /// In en, this message translates to:
+ /// **'Enter amounts in the same direction as the original transaction. Use a minus sign for a part that goes the other way.'**
+ String get splitEditorAmountHelper;
+
+ /// Validation error for an empty split amount.
+ ///
+ /// In en, this message translates to:
+ /// **'Amount is required'**
+ String get splitEditorAmountRequired;
+
+ /// Validation error for an unparseable split amount.
+ ///
+ /// In en, this message translates to:
+ /// **'Enter a valid amount'**
+ String get splitEditorAmountInvalid;
+
+ /// Validation error for a zero split amount.
+ ///
+ /// In en, this message translates to:
+ /// **'Amount can\'t be zero'**
+ String get splitEditorAmountZero;
+
+ /// Validation error when a split amount has more decimals than the currency allows.
+ ///
+ /// In en, this message translates to:
+ /// **'Use at most {decimals} decimal places'**
+ String splitEditorAmountTooPrecise(int decimals);
+
+ /// Label for a split row's category picker.
+ ///
+ /// In en, this message translates to:
+ /// **'Category'**
+ String get splitEditorCategoryLabel;
+
+ /// Button that adds a row to the split editor.
+ ///
+ /// In en, this message translates to:
+ /// **'Add split'**
+ String get splitEditorAddRow;
+
+ /// Tooltip for the button that removes a split row.
+ ///
+ /// In en, this message translates to:
+ /// **'Remove split'**
+ String get splitEditorRemoveRow;
+
+ /// Label of the remaining-to-allocate indicator.
+ ///
+ /// In en, this message translates to:
+ /// **'Remaining'**
+ String get splitEditorRemaining;
+
+ /// Shown while the split rows do not add up to the original amount.
+ ///
+ /// In en, this message translates to:
+ /// **'Split amounts must equal the original transaction amount.'**
+ String get splitEditorAmountsMustMatch;
+
+ /// Save button label when creating a split.
+ ///
+ /// In en, this message translates to:
+ /// **'Split transaction'**
+ String get splitEditorSubmitNew;
+
+ /// Save button label when editing a split.
+ ///
+ /// In en, this message translates to:
+ /// **'Update split'**
+ String get splitEditorSubmitEdit;
+
+ /// Snackbar after a split is created.
+ ///
+ /// In en, this message translates to:
+ /// **'Transaction split successfully'**
+ String get splitEditorSaved;
+
+ /// Snackbar after a split is updated.
+ ///
+ /// In en, this message translates to:
+ /// **'Split updated successfully'**
+ String get splitEditorUpdated;
+
+ /// Fallback snackbar when saving a split fails.
+ ///
+ /// In en, this message translates to:
+ /// **'Failed to save split'**
+ String get splitEditorSaveFailed;
+
+ /// Shown in the split editor while offline.
+ ///
+ /// In en, this message translates to:
+ /// **'You\'re offline. Splits can only be saved while connected.'**
+ String get splitEditorOffline;
+
+ /// Snackbar when deleting a split parent or child directly.
+ ///
+ /// In en, this message translates to:
+ /// **'Unsplit this transaction before deleting it.'**
+ String get transactionsListSplitDeleteBlocked;
+
+ /// Snackbar when a delete is blocked because the split lookup failed while online.
+ ///
+ /// In en, this message translates to:
+ /// **'Couldn\'t check whether this transaction is split. Please try again.'**
+ String get transactionsListSplitStatusUnknown;
}
class _AppLocalizationsDelegate
diff --git a/mobile/lib/l10n/app_localizations_en.dart b/mobile/lib/l10n/app_localizations_en.dart
index 923e79d0c2..26d821b01d 100644
--- a/mobile/lib/l10n/app_localizations_en.dart
+++ b/mobile/lib/l10n/app_localizations_en.dart
@@ -1247,4 +1247,152 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get cashFlowTransactionsLoadFailed => 'Couldn\'t load transactions';
+
+ @override
+ String get splitBadge => 'Split';
+
+ @override
+ String get splitSectionTitle => 'Split entries';
+
+ @override
+ String get splitSectionDescription =>
+ 'This transaction has been split into the following entries.';
+
+ @override
+ String get splitChildTitle => 'Part of split';
+
+ @override
+ String get splitChildDescription =>
+ 'This entry is part of a split transaction. Edit the split to change it.';
+
+ @override
+ String get splitChildEditLocked =>
+ 'Split entries can\'t be edited directly. Use Edit split below.';
+
+ @override
+ String get splitStatusUnknownLocked =>
+ 'Checking whether this transaction is split. The fields stay locked until that finishes.';
+
+ @override
+ String get splitUncategorized => '(uncategorized)';
+
+ @override
+ String get splitTransactionButton => 'Split transaction';
+
+ @override
+ String get splitTransactionDescription =>
+ 'Split this transaction into multiple entries with different categories and amounts.';
+
+ @override
+ String get splitEditButton => 'Edit split';
+
+ @override
+ String get splitUnsplitButton => 'Unsplit';
+
+ @override
+ String get splitUnsplitTitle => 'Unsplit transaction';
+
+ @override
+ String get splitUnsplitConfirm =>
+ 'This will remove all split entries and restore the original transaction.';
+
+ @override
+ String get splitUnsplitSuccess => 'Transaction unsplit successfully';
+
+ @override
+ String get splitUnsplitFailed => 'Failed to unsplit transaction';
+
+ @override
+ String get splitOfflineNotice =>
+ 'Connect to the internet to load or edit split details.';
+
+ @override
+ String get splitLoadFailed => 'Couldn\'t load split details.';
+
+ @override
+ String get splitEditorNewTitle => 'Split transaction';
+
+ @override
+ String get splitEditorEditTitle => 'Edit split';
+
+ @override
+ String get splitEditorOriginalAmount => 'Original amount';
+
+ @override
+ String splitEditorRowLabel(int number) {
+ return 'Split #$number';
+ }
+
+ @override
+ String get splitEditorNameLabel => 'Name';
+
+ @override
+ String get splitEditorNamePlaceholder => 'Split name';
+
+ @override
+ String get splitEditorNameRequired => 'Name is required';
+
+ @override
+ String get splitEditorAmountLabel => 'Amount';
+
+ @override
+ String get splitEditorAmountHelper =>
+ 'Enter amounts in the same direction as the original transaction. Use a minus sign for a part that goes the other way.';
+
+ @override
+ String get splitEditorAmountRequired => 'Amount is required';
+
+ @override
+ String get splitEditorAmountInvalid => 'Enter a valid amount';
+
+ @override
+ String get splitEditorAmountZero => 'Amount can\'t be zero';
+
+ @override
+ String splitEditorAmountTooPrecise(int decimals) {
+ return 'Use at most $decimals decimal places';
+ }
+
+ @override
+ String get splitEditorCategoryLabel => 'Category';
+
+ @override
+ String get splitEditorAddRow => 'Add split';
+
+ @override
+ String get splitEditorRemoveRow => 'Remove split';
+
+ @override
+ String get splitEditorRemaining => 'Remaining';
+
+ @override
+ String get splitEditorAmountsMustMatch =>
+ 'Split amounts must equal the original transaction amount.';
+
+ @override
+ String get splitEditorSubmitNew => 'Split transaction';
+
+ @override
+ String get splitEditorSubmitEdit => 'Update split';
+
+ @override
+ String get splitEditorSaved => 'Transaction split successfully';
+
+ @override
+ String get splitEditorUpdated => 'Split updated successfully';
+
+ @override
+ String get splitEditorSaveFailed => 'Failed to save split';
+
+ @override
+ String get splitEditorOffline =>
+ 'You\'re offline. Splits can only be saved while connected.';
+
+ @override
+ String get transactionsListSplitDeleteBlocked =>
+ 'Unsplit this transaction before deleting it.';
+
+ @override
+ String get transactionsListSplitStatusUnknown =>
+ 'Couldn\'t check whether this transaction is split. Please try again.';
}
diff --git a/mobile/lib/l10n/app_localizations_sv.dart b/mobile/lib/l10n/app_localizations_sv.dart
index 1c3942acbe..cd665a8b50 100644
--- a/mobile/lib/l10n/app_localizations_sv.dart
+++ b/mobile/lib/l10n/app_localizations_sv.dart
@@ -1261,4 +1261,152 @@ class AppLocalizationsSv extends AppLocalizations {
@override
String get cashFlowTransactionsLoadFailed =>
'Kunde inte läsa in transaktioner';
+
+ @override
+ String get splitBadge => 'Delad';
+
+ @override
+ String get splitSectionTitle => 'Delade poster';
+
+ @override
+ String get splitSectionDescription =>
+ 'Den här transaktionen har delats upp i följande poster.';
+
+ @override
+ String get splitChildTitle => 'Del av uppdelning';
+
+ @override
+ String get splitChildDescription =>
+ 'Den här posten är en del av en uppdelad transaktion. Redigera uppdelningen för att ändra den.';
+
+ @override
+ String get splitChildEditLocked =>
+ 'Delade poster kan inte redigeras direkt. Använd Redigera uppdelning nedan.';
+
+ @override
+ String get splitStatusUnknownLocked =>
+ 'Kontrollerar om transaktionen är uppdelad. Fälten är låsta tills det är klart.';
+
+ @override
+ String get splitUncategorized => '(okategoriserad)';
+
+ @override
+ String get splitTransactionButton => 'Dela upp transaktion';
+
+ @override
+ String get splitTransactionDescription =>
+ 'Dela upp transaktionen i flera poster med olika kategorier och belopp.';
+
+ @override
+ String get splitEditButton => 'Redigera uppdelning';
+
+ @override
+ String get splitUnsplitButton => 'Ta bort uppdelning';
+
+ @override
+ String get splitUnsplitTitle => 'Ta bort uppdelning';
+
+ @override
+ String get splitUnsplitConfirm =>
+ 'Detta tar bort alla delade poster och återställer den ursprungliga transaktionen.';
+
+ @override
+ String get splitUnsplitSuccess => 'Uppdelningen har tagits bort';
+
+ @override
+ String get splitUnsplitFailed => 'Det gick inte att ta bort uppdelningen';
+
+ @override
+ String get splitOfflineNotice =>
+ 'Anslut till internet för att läsa in eller redigera uppdelningar.';
+
+ @override
+ String get splitLoadFailed => 'Det gick inte att läsa in uppdelningen.';
+
+ @override
+ String get splitEditorNewTitle => 'Dela upp transaktion';
+
+ @override
+ String get splitEditorEditTitle => 'Redigera uppdelning';
+
+ @override
+ String get splitEditorOriginalAmount => 'Ursprungligt belopp';
+
+ @override
+ String splitEditorRowLabel(int number) {
+ return 'Del $number';
+ }
+
+ @override
+ String get splitEditorNameLabel => 'Namn';
+
+ @override
+ String get splitEditorNamePlaceholder => 'Namn på delen';
+
+ @override
+ String get splitEditorNameRequired => 'Namn krävs';
+
+ @override
+ String get splitEditorAmountLabel => 'Belopp';
+
+ @override
+ String get splitEditorAmountHelper =>
+ 'Ange belopp i samma riktning som den ursprungliga transaktionen. Använd minustecken för en del som går åt andra hållet.';
+
+ @override
+ String get splitEditorAmountRequired => 'Belopp krävs';
+
+ @override
+ String get splitEditorAmountInvalid => 'Ange ett giltigt belopp';
+
+ @override
+ String get splitEditorAmountZero => 'Beloppet kan inte vara noll';
+
+ @override
+ String splitEditorAmountTooPrecise(int decimals) {
+ return 'Använd högst $decimals decimaler';
+ }
+
+ @override
+ String get splitEditorCategoryLabel => 'Kategori';
+
+ @override
+ String get splitEditorAddRow => 'Lägg till del';
+
+ @override
+ String get splitEditorRemoveRow => 'Ta bort del';
+
+ @override
+ String get splitEditorRemaining => 'Återstår';
+
+ @override
+ String get splitEditorAmountsMustMatch =>
+ 'Delbeloppen måste vara lika med transaktionens ursprungliga belopp.';
+
+ @override
+ String get splitEditorSubmitNew => 'Dela upp transaktion';
+
+ @override
+ String get splitEditorSubmitEdit => 'Uppdatera uppdelning';
+
+ @override
+ String get splitEditorSaved => 'Transaktionen har delats upp';
+
+ @override
+ String get splitEditorUpdated => 'Uppdelningen har uppdaterats';
+
+ @override
+ String get splitEditorSaveFailed => 'Det gick inte att spara uppdelningen';
+
+ @override
+ String get splitEditorOffline =>
+ 'Du är offline. Uppdelningar kan bara sparas när du är ansluten.';
+
+ @override
+ String get transactionsListSplitDeleteBlocked =>
+ 'Ta bort uppdelningen innan du tar bort transaktionen.';
+
+ @override
+ String get transactionsListSplitStatusUnknown =>
+ 'Det gick inte att kontrollera om transaktionen är uppdelad. Försök igen.';
}
diff --git a/mobile/lib/l10n/app_sv.arb b/mobile/lib/l10n/app_sv.arb
index 6466d40555..b89c6cc3bc 100644
--- a/mobile/lib/l10n/app_sv.arb
+++ b/mobile/lib/l10n/app_sv.arb
@@ -365,5 +365,50 @@
"cashFlowOffline": "Du är offline. Kassaflödet beräknas av din Sure-server och kräver en anslutning.",
"cashFlowOutdated": "Inaktuell",
"cashFlowTransactionsEmpty": "Inga transaktioner under perioden",
- "cashFlowTransactionsLoadFailed": "Kunde inte läsa in transaktioner"
+ "cashFlowTransactionsLoadFailed": "Kunde inte läsa in transaktioner",
+
+"splitBadge": "Delad",
+ "splitSectionTitle": "Delade poster",
+ "splitSectionDescription": "Den här transaktionen har delats upp i följande poster.",
+ "splitChildTitle": "Del av uppdelning",
+ "splitChildDescription": "Den här posten är en del av en uppdelad transaktion. Redigera uppdelningen för att ändra den.",
+ "splitChildEditLocked": "Delade poster kan inte redigeras direkt. Använd Redigera uppdelning nedan.",
+ "splitStatusUnknownLocked": "Kontrollerar om transaktionen är uppdelad. Fälten är låsta tills det är klart.",
+ "splitUncategorized": "(okategoriserad)",
+ "splitTransactionButton": "Dela upp transaktion",
+ "splitTransactionDescription": "Dela upp transaktionen i flera poster med olika kategorier och belopp.",
+ "splitEditButton": "Redigera uppdelning",
+ "splitUnsplitButton": "Ta bort uppdelning",
+ "splitUnsplitTitle": "Ta bort uppdelning",
+ "splitUnsplitConfirm": "Detta tar bort alla delade poster och återställer den ursprungliga transaktionen.",
+ "splitUnsplitSuccess": "Uppdelningen har tagits bort",
+ "splitUnsplitFailed": "Det gick inte att ta bort uppdelningen",
+ "splitOfflineNotice": "Anslut till internet för att läsa in eller redigera uppdelningar.",
+ "splitLoadFailed": "Det gick inte att läsa in uppdelningen.",
+ "splitEditorNewTitle": "Dela upp transaktion",
+ "splitEditorEditTitle": "Redigera uppdelning",
+ "splitEditorOriginalAmount": "Ursprungligt belopp",
+ "splitEditorRowLabel": "Del {number}",
+ "splitEditorNameLabel": "Namn",
+ "splitEditorNamePlaceholder": "Namn på delen",
+ "splitEditorNameRequired": "Namn krävs",
+ "splitEditorAmountLabel": "Belopp",
+ "splitEditorAmountHelper": "Ange belopp i samma riktning som den ursprungliga transaktionen. Använd minustecken för en del som går åt andra hållet.",
+ "splitEditorAmountRequired": "Belopp krävs",
+ "splitEditorAmountInvalid": "Ange ett giltigt belopp",
+ "splitEditorAmountZero": "Beloppet kan inte vara noll",
+ "splitEditorAmountTooPrecise": "Använd högst {decimals} decimaler",
+ "splitEditorCategoryLabel": "Kategori",
+ "splitEditorAddRow": "Lägg till del",
+ "splitEditorRemoveRow": "Ta bort del",
+ "splitEditorRemaining": "Återstår",
+ "splitEditorAmountsMustMatch": "Delbeloppen måste vara lika med transaktionens ursprungliga belopp.",
+ "splitEditorSubmitNew": "Dela upp transaktion",
+ "splitEditorSubmitEdit": "Uppdatera uppdelning",
+ "splitEditorSaved": "Transaktionen har delats upp",
+ "splitEditorUpdated": "Uppdelningen har uppdaterats",
+ "splitEditorSaveFailed": "Det gick inte att spara uppdelningen",
+ "splitEditorOffline": "Du är offline. Uppdelningar kan bara sparas när du är ansluten.",
+ "transactionsListSplitDeleteBlocked": "Ta bort uppdelningen innan du tar bort transaktionen.",
+ "transactionsListSplitStatusUnknown": "Det gick inte att kontrollera om transaktionen är uppdelad. Försök igen."
}
diff --git a/mobile/lib/main.dart b/mobile/lib/main.dart
index 7662bf71b7..448a522b37 100644
--- a/mobile/lib/main.dart
+++ b/mobile/lib/main.dart
@@ -8,6 +8,7 @@ import 'providers/categories_provider.dart';
import 'providers/merchants_provider.dart';
import 'providers/tags_provider.dart';
import 'providers/transactions_provider.dart';
+import 'providers/transaction_splits_provider.dart';
import 'providers/chat_provider.dart';
import 'providers/theme_provider.dart';
import 'providers/privacy_provider.dart';
@@ -98,6 +99,15 @@ class SureApp extends StatelessWidget {
}
},
),
+ ChangeNotifierProxyProvider<ConnectivityService,
+ TransactionSplitsProvider>(
+ create: (_) => TransactionSplitsProvider(),
+ update: (_, connectivityService, splitsProvider) {
+ final provider = splitsProvider ?? TransactionSplitsProvider();
+ provider.setConnectivityService(connectivityService);
+ return provider;
+ },
+ ),
],
child: Consumer<ThemeProvider>(
builder: (context, themeProvider, _) => MaterialApp(
diff --git a/mobile/lib/models/offline_transaction.dart b/mobile/lib/models/offline_transaction.dart
index 1fafd40a5a..5a221d6e53 100644
--- a/mobile/lib/models/offline_transaction.dart
+++ b/mobile/lib/models/offline_transaction.dart
@@ -34,6 +34,10 @@ class OfflineTransaction extends Transaction {
super.tagIds,
super.tagNames,
super.tagsProvided = true,
+ super.amountDecimal,
+ super.kind,
+ super.excluded,
+ super.splitParent,
this.syncStatus = SyncStatus.pending,
DateTime? createdAt,
DateTime? updatedAt,
@@ -64,6 +68,10 @@ class OfflineTransaction extends Transaction {
tagIds: transaction.tagIds,
tagNames: transaction.tagNames,
tagsProvided: transaction.tagsProvided,
+ amountDecimal: transaction.amountDecimal,
+ kind: transaction.kind,
+ excluded: transaction.excluded,
+ splitParent: transaction.splitParent,
syncStatus: syncStatus,
);
}
@@ -91,6 +99,10 @@ class OfflineTransaction extends Transaction {
tagIds: tagIds,
tagNames: tagNames,
tagsProvided: tagsProvided,
+ amountDecimal: map['amount_decimal'] as String?,
+ kind: map['kind'] as String?,
+ excluded: _decodeBool(map['excluded']),
+ splitParent: _decodeBool(map['split_parent']),
syncStatus: _parseSyncStatus(map['sync_status'] as String),
createdAt: DateTime.parse(map['created_at'] as String),
updatedAt: DateTime.parse(map['updated_at'] as String),
@@ -114,6 +126,10 @@ class OfflineTransaction extends Transaction {
'merchant_name': merchantName,
'tag_ids': jsonEncode(tagIds),
'tag_names': jsonEncode(tagNames),
+ 'amount_decimal': amountDecimal,
+ 'kind': kind,
+ 'excluded': _encodeBool(excluded),
+ 'split_parent': _encodeBool(splitParent),
'sync_status': _syncStatusToString(syncStatus),
'created_at': createdAt.toIso8601String(),
'updated_at': updatedAt.toIso8601String(),
@@ -139,6 +155,10 @@ class OfflineTransaction extends Transaction {
tagIds: tagIds,
tagNames: tagNames,
tagsProvided: tagsProvided,
+ amountDecimal: amountDecimal,
+ kind: kind,
+ excluded: excluded,
+ splitParent: splitParent,
);
}
@@ -176,6 +196,10 @@ class OfflineTransaction extends Transaction {
tagIds: nextTagIds,
tagNames: nextTagIds.map((tagId) => tagNamesById[tagId] ?? '').toList(),
tagsProvided: true,
+ amountDecimal: amountDecimal,
+ kind: kind,
+ excluded: excluded,
+ splitParent: splitParent,
);
}
@@ -205,6 +229,13 @@ class OfflineTransaction extends Transaction {
: merchantName,
tagIds: transaction.tagsProvided ? transaction.tagIds : tagIds,
tagNames: transaction.tagsProvided ? transaction.tagNames : tagNames,
+ // An older server leaves these out; the cached value came from the same
+ // server, so it is null too unless the amount is unchanged.
+ amountDecimal: transaction.amountDecimal ??
+ (transaction.amount == amount ? amountDecimal : null),
+ kind: transaction.kind ?? kind,
+ excluded: transaction.excluded ?? excluded,
+ splitParent: transaction.splitParent ?? splitParent,
syncStatus: SyncStatus.synced,
createdAt: createdAt,
updatedAt: DateTime.now(),
@@ -230,10 +261,17 @@ class OfflineTransaction extends Transaction {
List<String>? tagIds,
List<String>? tagNames,
bool? tagsProvided,
+ String? amountDecimal,
+ String? kind,
+ bool? excluded,
+ bool? splitParent,
SyncStatus? syncStatus,
DateTime? createdAt,
DateTime? updatedAt,
}) {
+ // A new display amount without a new exact amount makes the cached exact
+ // amount stale.
+ final amountChanged = amount != null && amount != this.amount;
return OfflineTransaction(
id: id ?? this.id,
localId: localId ?? this.localId,
@@ -253,6 +291,11 @@ class OfflineTransaction extends Transaction {
tagIds: tagIds ?? this.tagIds,
tagNames: tagNames ?? this.tagNames,
tagsProvided: tagsProvided ?? this.tagsProvided,
+ amountDecimal:
+ amountDecimal ?? (amountChanged ? null : this.amountDecimal),
+ kind: kind ?? this.kind,
+ excluded: excluded ?? this.excluded,
+ splitParent: splitParent ?? this.splitParent,
syncStatus: syncStatus ?? this.syncStatus,
createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt,
@@ -298,6 +341,15 @@ class OfflineTransaction extends Transaction {
return const [];
}
+ static bool? _decodeBool(Object? value) {
+ if (value is bool) return value;
+ if (value is int) return value != 0;
+ return null;
+ }
+
+ static int? _encodeBool(bool? value) =>
+ value == null ? null : (value ? 1 : 0);
+
static String _syncStatusToString(SyncStatus status) {
switch (status) {
case SyncStatus.synced:
diff --git a/mobile/lib/models/transaction_split.dart b/mobile/lib/models/transaction_split.dart
new file mode 100644
index 0000000000..d978434978
--- /dev/null
+++ b/mobile/lib/models/transaction_split.dart
@@ -0,0 +1,105 @@
+import '../utils/split_math.dart';
+import 'transaction.dart';
+
+/// One child of a split, as returned by `GET /api/v1/transactions/:id/split`.
+///
+/// [transaction] carries the regular transaction payload (name, category,
+/// display-formatted amount). [amountDecimal] is the exact stored amount,
+/// which is what a replacement split has to send back.
+class TransactionSplitChild {
+ final Transaction transaction;
+ final String amountDecimal;
+ final bool excluded;
+
+ const TransactionSplitChild({
+ required this.transaction,
+ required this.amountDecimal,
+ this.excluded = false,
+ });
+
+ factory TransactionSplitChild.fromJson(Map<String, dynamic> json) {
+ return TransactionSplitChild(
+ transaction: Transaction.fromJson(json),
+ amountDecimal: json['amount_decimal']?.toString() ?? '0',
+ excluded: json['excluded'] == true,
+ );
+ }
+
+ String? get id => transaction.id;
+ String get name => transaction.name;
+ String? get categoryId => transaction.categoryId;
+ String? get categoryName => transaction.categoryName;
+
+ /// Exact amount in [SplitMath.scale] units, using the API sign convention
+ /// (expenses positive, income negative).
+ BigInt get amountUnits => SplitMath.parseUnits(amountDecimal) ?? BigInt.zero;
+}
+
+/// A split parent and its children.
+class TransactionSplit {
+ final String transactionId;
+
+ /// Display-formatted parent amount (rounded to currency precision).
+ final String amount;
+
+ /// Exact stored parent amount; the children must sum to this.
+ final String amountDecimal;
+ final String currency;
+ final List<TransactionSplitChild> children;
+
+ TransactionSplit({
+ required this.transactionId,
+ required this.amount,
+ required this.amountDecimal,
+ required this.currency,
+ required List<TransactionSplitChild> children,
+ }) : children = List.unmodifiable(children);
+
+ factory TransactionSplit.fromJson(Map<String, dynamic> json) {
+ final rawChildren = json['children'];
+ return TransactionSplit(
+ transactionId: json['transaction_id']?.toString() ?? '',
+ amount: json['amount']?.toString() ?? '',
+ amountDecimal: json['amount_decimal']?.toString() ?? '0',
+ currency: json['currency']?.toString() ?? '',
+ children: rawChildren is List
+ ? rawChildren
+ .whereType<Map>()
+ .map((child) => TransactionSplitChild.fromJson(
+ Map<String, dynamic>.from(child),
+ ))
+ .toList()
+ : const [],
+ );
+ }
+
+ BigInt get amountUnits => SplitMath.parseUnits(amountDecimal) ?? BigInt.zero;
+
+ List<String> get childIds =>
+ children.map((c) => c.id).whereType<String>().toList();
+}
+
+/// One row the user submits when creating or replacing a split.
+///
+/// [amount] is a plain decimal string in the API's sign convention (same sign
+/// as the parent's stored amount).
+class SplitRowInput {
+ final String name;
+ final String amount;
+ final String? categoryId;
+ final bool excluded;
+
+ const SplitRowInput({
+ required this.name,
+ required this.amount,
+ this.categoryId,
+ this.excluded = false,
+ });
+
+ Map<String, dynamic> toJson() => {
+ 'name': name,
+ 'amount': amount,
+ 'category_id': categoryId,
+ if (excluded) 'excluded': true,
+ };
+}
diff --git a/mobile/lib/providers/transaction_splits_provider.dart b/mobile/lib/providers/transaction_splits_provider.dart
new file mode 100644
index 0000000000..4bf5468a50
--- /dev/null
+++ b/mobile/lib/providers/transaction_splits_provider.dart
@@ -0,0 +1,423 @@
+import 'package:flutter/foundation.dart';
+
+import '../models/transaction_split.dart';
+import '../services/connectivity_service.dart';
+import '../services/log_service.dart';
+import '../services/transaction_splits_service.dart';
+import '../utils/split_list_grouping.dart';
+
+/// Outcome of a split write (create, replace, or unsplit).
+class SplitActionResult {
+ final bool success;
+ final TransactionSplit? split;
+ final String? error;
+
+ /// Server ids of children that no longer exist after this action. Callers
+ /// drop them from the offline cache, since an account-scoped sync only
+ /// upserts and would otherwise leave them behind.
+ final List<String> removedChildIds;
+
+ const SplitActionResult({
+ required this.success,
+ this.split,
+ this.error,
+ this.removedChildIds = const [],
+ });
+}
+
+/// Whether a transaction may be deleted like a plain one, as far as splits go.
+enum SplitDeleteStatus {
+ /// Not split (confirmed by the server, or offline with nothing cached).
+ allowed,
+
+ /// A split parent or child: it has to be unsplit first.
+ split,
+
+ /// Online, but the split lookup failed, so deleting could cascade to
+ /// children this device does not know about.
+ unknown,
+}
+
+/// Loads and edits transaction splits, and remembers the split structure it
+/// has seen so the transaction list can group children under their parent.
+///
+/// Splits are online-only: the offline queue only replays creates and
+/// deletes, so writes are refused while offline instead of being queued.
+class TransactionSplitsProvider with ChangeNotifier implements SplitLookup {
+ TransactionSplitsProvider({TransactionSplitsService? service})
+ : _service = service ?? TransactionSplitsService();
+
+ final TransactionSplitsService _service;
+ final LogService _log = LogService.instance;
+
+ final Map<String, TransactionSplit> _splitsByParent = {};
+ final Map<String, String> _parentByChild = {};
+
+ /// Transactions whose split membership (parent, child, or not split) has
+ /// been confirmed by the server in this session.
+ final Set<String> _known = {};
+ final Set<String> _failedLookups = {};
+
+ /// In-flight lookups per transaction; a count, so one of two overlapping
+ /// lookups finishing does not hide the other's loading state.
+ final Map<String, int> _loading = {};
+ ConnectivityService? _connectivityService;
+ bool _isDisposed = false;
+
+ /// Bumped by [clear]. Requests that started before a clear must not write
+ /// their result back into the reset cache.
+ int _generation = 0;
+
+ static const offlineError = 'offline';
+
+ /// Follows [service] so split widgets rebuild when connectivity changes;
+ /// the proxy provider keeps this instance, so nothing else notifies them.
+ void setConnectivityService(ConnectivityService service) {
+ if (identical(service, _connectivityService)) return;
+ _connectivityService?.removeListener(_onConnectivityChanged);
+ _connectivityService = service;
+ service.addListener(_onConnectivityChanged);
+ }
+
+ void _onConnectivityChanged() => _notify();
+
+ bool get isOnline => _connectivityService?.isOnline ?? true;
+
+ bool isLoading(String transactionId) => _loading.containsKey(transactionId);
+
+ /// The split [transactionId] belongs to, as parent or child, if known.
+ TransactionSplit? splitFor(String transactionId) {
+ final direct = _splitsByParent[transactionId];
+ if (direct != null) return direct;
+ final parentId = _parentByChild[transactionId];
+ return parentId == null ? null : _splitsByParent[parentId];
+ }
+
+ @override
+ List<String>? childIdsFor(String parentId) =>
+ _splitsByParent[parentId]?.childIds;
+
+ @override
+ bool isSplitParent(String transactionId) =>
+ _splitsByParent.containsKey(transactionId);
+
+ bool isSplitChild(String transactionId) =>
+ _parentByChild.containsKey(transactionId);
+
+ /// Whether the server has confirmed if [transactionId] is a split parent,
+ /// a split child, or not split. Until then, edits that the API rejects for
+ /// split children must stay locked.
+ @override
+ bool isSplitStatusKnown(String transactionId) =>
+ _known.contains(transactionId);
+
+ /// Whether the edit form may be used: the split status is known, or its
+ /// lookup failed (the server still rejects direct edits of split children).
+ bool canEditAfterLookup(String transactionId) =>
+ _known.contains(transactionId) || _failedLookups.contains(transactionId);
+
+ String? parentIdFor(String childId) => _parentByChild[childId];
+
+ /// A failed lookup must not lock editing of an ordinary transaction: let
+ /// the user proceed, since the server still rejects direct edits of split
+ /// children. Only transactions with no cached split are unlocked, and the
+ /// lookup is retried the next time the screen loads.
+ void _allowEditingAfterFailedLookup(String transactionId) {
+ if (splitFor(transactionId) == null) _failedLookups.add(transactionId);
+ }
+
+ /// Fetches the split for [transactionId]. Returns null when it is not split.
+ /// When the request fails (or the device is offline), the cached split, if
+ /// any, is returned and [isSplitStatusKnown] stays false.
+ Future<TransactionSplit?> loadSplit({
+ required String accessToken,
+ required String transactionId,
+ }) async {
+ await _lookup(accessToken: accessToken, transactionId: transactionId);
+ return splitFor(transactionId);
+ }
+
+ /// Asks the server for [transactionId]'s split membership and records it.
+ /// Returns true only when the server answered.
+ Future<bool> _lookup({
+ required String accessToken,
+ required String transactionId,
+ }) async {
+ if (!isOnline) return false;
+
+ final generation = _generation;
+ _loading.update(transactionId, (n) => n + 1, ifAbsent: () => 1);
+ _notify();
+
+ try {
+ final result = await _service.getSplit(
+ accessToken: accessToken,
+ transactionId: transactionId,
+ );
+ if (generation != _generation) return false;
+ if (result['success'] == true) {
+ final split = result['split'] as TransactionSplit?;
+ if (split == null) {
+ _forget(transactionId);
+ } else {
+ _remember(split);
+ }
+ _known.add(transactionId);
+ _failedLookups.remove(transactionId);
+ return true;
+ }
+ _log.error(
+ 'TransactionSplitsProvider',
+ 'loadSplit failed: ${result['error'] ?? 'no error message'}',
+ );
+ _allowEditingAfterFailedLookup(transactionId);
+ return false;
+ } catch (e) {
+ _log.error(
+ 'TransactionSplitsProvider',
+ 'loadSplit failed with ${e.runtimeType}',
+ );
+ if (generation != _generation) return false;
+ _allowEditingAfterFailedLookup(transactionId);
+ return false;
+ } finally {
+ if (generation == _generation) {
+ final remaining = (_loading[transactionId] ?? 1) - 1;
+ if (remaining > 0) {
+ _loading[transactionId] = remaining;
+ } else {
+ _loading.remove(transactionId);
+ }
+ }
+ _notify();
+ }
+ }
+
+ /// Looks up the splits of rows the transactions index flags as split
+ /// parents, so the list can group their children under them. One request
+ /// at a time and at most [limit] per call, to stay well inside the API rate
+ /// limit; rows already known, in flight, or whose lookup failed this
+ /// session are skipped.
+ Future<void> loadFlaggedParents({
+ required String accessToken,
+ required Iterable<String> transactionIds,
+ int limit = 20,
+ }) async {
+ final generation = _generation;
+ var requested = 0;
+ for (final id in transactionIds) {
+ if (requested >= limit || !isOnline || generation != _generation) {
+ return;
+ }
+ if (_known.contains(id) ||
+ _loading.containsKey(id) ||
+ _flaggedLookupFailed.contains(id)) {
+ continue;
+ }
+ requested++;
+ final ok = await _lookup(accessToken: accessToken, transactionId: id);
+ if (!ok && generation == _generation) _flaggedLookupFailed.add(id);
+ }
+ }
+
+ /// Flagged parents whose background lookup failed; not retried
+ /// automatically until [clear], so a failing server isn't polled on every
+ /// list refresh. Opening the transaction still looks it up.
+ final Set<String> _flaggedLookupFailed = {};
+
+ /// Decides whether [transactionId] may go through the plain delete
+ /// endpoint. The server refuses a split child and cascades a split parent's
+ /// delete to its children, which an upsert-only sync would leave behind.
+ ///
+ /// Online, membership is looked up first: always when [fresh] is true (the
+ /// row may have been split on the web or another device since it was last
+ /// seen), otherwise only when it is not known yet. A failed lookup returns
+ /// [SplitDeleteStatus.unknown] so the caller blocks the delete. Offline,
+ /// only splits already known on this device are blocked, so offline delete
+ /// keeps working. Callers also block rows the index flags as split parents
+ /// (`split_parent`); split children carry no such flag.
+ Future<SplitDeleteStatus> checkBeforeDelete({
+ required String? accessToken,
+ required String transactionId,
+ bool fresh = false,
+ }) async {
+ if (isOnline && (fresh || !_known.contains(transactionId))) {
+ if (accessToken == null) return SplitDeleteStatus.unknown;
+ final ok = await _lookup(
+ accessToken: accessToken,
+ transactionId: transactionId,
+ );
+ if (!ok) return SplitDeleteStatus.unknown;
+ }
+ if (isSplitParent(transactionId) || isSplitChild(transactionId)) {
+ return SplitDeleteStatus.split;
+ }
+ return SplitDeleteStatus.allowed;
+ }
+
+ /// Creates a split, or replaces the existing one when [replace] is true.
+ Future<SplitActionResult> saveSplit({
+ required String accessToken,
+ required String transactionId,
+ required List<SplitRowInput> rows,
+ required bool replace,
+ }) async {
+ if (!isOnline) {
+ return const SplitActionResult(success: false, error: offlineError);
+ }
+
+ final previous = splitFor(transactionId);
+ final generation = _generation;
+ try {
+ final result = replace
+ ? await _service.updateSplit(
+ accessToken: accessToken,
+ transactionId: transactionId,
+ rows: rows,
+ )
+ : await _service.createSplit(
+ accessToken: accessToken,
+ transactionId: transactionId,
+ rows: rows,
+ );
+
+ if (result['success'] != true) {
+ return SplitActionResult(
+ success: false,
+ error: _displayableError(result['error'] as String?, 'saveSplit'),
+ );
+ }
+
+ final split = result['split'] as TransactionSplit;
+ final newIds = split.childIds.toSet();
+ final removed = (previous?.childIds ?? const <String>[])
+ .where((id) => !newIds.contains(id))
+ .toList();
+ if (generation == _generation) {
+ if (previous != null) _forget(previous.transactionId);
+ _remember(split);
+ _notify();
+ }
+ return SplitActionResult(
+ success: true,
+ split: split,
+ removedChildIds: removed,
+ );
+ } catch (e) {
+ _log.error(
+ 'TransactionSplitsProvider',
+ 'saveSplit failed with ${e.runtimeType}',
+ );
+ return const SplitActionResult(success: false);
+ }
+ }
+
+ /// Removes the split [transactionId] belongs to.
+ Future<SplitActionResult> unsplit({
+ required String accessToken,
+ required String transactionId,
+ }) async {
+ if (!isOnline) {
+ return const SplitActionResult(success: false, error: offlineError);
+ }
+
+ final previous = splitFor(transactionId);
+ final generation = _generation;
+ try {
+ final result = await _service.deleteSplit(
+ accessToken: accessToken,
+ transactionId: transactionId,
+ );
+ if (result['success'] != true) {
+ return SplitActionResult(
+ success: false,
+ error: _displayableError(result['error'] as String?, 'unsplit'),
+ );
+ }
+
+ if (generation == _generation) {
+ if (previous != null) _forget(previous.transactionId);
+ _forget(transactionId);
+ _notify();
+ }
+ return SplitActionResult(
+ success: true,
+ removedChildIds: previous?.childIds ?? const [],
+ );
+ } catch (e) {
+ _log.error(
+ 'TransactionSplitsProvider',
+ 'unsplit failed with ${e.runtimeType}',
+ );
+ return const SplitActionResult(success: false);
+ }
+ }
+
+ /// Seeds the cache directly (used by tests and after a successful write).
+ @visibleForTesting
+ void remember(TransactionSplit split) {
+ _remember(split);
+ _notify();
+ }
+
+ /// Drops everything this provider learned (sign-out, clearing local
+ /// data). Lookups and writes still in flight finish without repopulating it.
+ void clear() {
+ _generation++;
+ _loading.clear();
+ _splitsByParent.clear();
+ _parentByChild.clear();
+ _known.clear();
+ _failedLookups.clear();
+ _flaggedLookupFailed.clear();
+ _notify();
+ }
+
+ /// Server validation messages are shown as they are. Session and transport
+ /// failures are logged and returned as null, so screens show their own
+ /// localized failure message instead.
+ String? _displayableError(String? error, String operation) {
+ if (error == null ||
+ error == 'unauthorized' ||
+ error.startsWith('Network error:')) {
+ _log.error(
+ 'TransactionSplitsProvider',
+ '$operation failed: ${error ?? 'no error message'}',
+ );
+ return null;
+ }
+ return error;
+ }
+
+ void _remember(TransactionSplit split) {
+ _forget(split.transactionId);
+ _splitsByParent[split.transactionId] = split;
+ _known.add(split.transactionId);
+ for (final childId in split.childIds) {
+ _parentByChild[childId] = split.transactionId;
+ _known.add(childId);
+ }
+ }
+
+ void _forget(String transactionId) {
+ final parentId = _parentByChild[transactionId] ?? transactionId;
+ final split = _splitsByParent.remove(parentId);
+ if (split != null) {
+ for (final childId in split.childIds) {
+ _parentByChild.remove(childId);
+ }
+ }
+ }
+
+ void _notify() {
+ if (!_isDisposed) notifyListeners();
+ }
+
+ @override
+ void dispose() {
+ _isDisposed = true;
+ _connectivityService?.removeListener(_onConnectivityChanged);
+ _connectivityService = null;
+ super.dispose();
+ }
+}
diff --git a/mobile/lib/providers/transactions_provider.dart b/mobile/lib/providers/transactions_provider.dart
index e273641032..f9a4b40d99 100644
--- a/mobile/lib/providers/transactions_provider.dart
+++ b/mobile/lib/providers/transactions_provider.dart
@@ -9,9 +9,15 @@ import '../services/connectivity_service.dart';
import '../services/log_service.dart';
class TransactionsProvider with ChangeNotifier {
+ TransactionsProvider({
+ OfflineStorageService? offlineStorage,
+ SyncService? syncService,
+ }) : _offlineStorage = offlineStorage ?? OfflineStorageService(),
+ _syncService = syncService ?? SyncService();
+
final TransactionsService _transactionsService = TransactionsService();
- final OfflineStorageService _offlineStorage = OfflineStorageService();
- final SyncService _syncService = SyncService();
+ final OfflineStorageService _offlineStorage;
+ final SyncService _syncService;
final LogService _log = LogService.instance;
List<OfflineTransaction> _transactions = [];
@@ -24,6 +30,19 @@ class TransactionsProvider with ChangeNotifier {
bool _isListenerAttached = false;
bool _isDisposed = false;
+ /// Split children the server destroyed (by a split replace or unsplit) in
+ /// this session. Account sync only upserts and a sync that started before
+ /// the split change can still return them, so they are dropped again after
+ /// every sync. Server ids are never reused, so keeping them is safe.
+ final Set<String> _destroyedSplitChildIds = {};
+
+ /// Accounts whose post-split refresh has not completed (offline or failed);
+ /// the next fetch for them syncs even when not forced.
+ final Set<String> _accountsNeedingResync = {};
+
+ /// Tail of the post-split refresh chain, so refreshes run one at a time.
+ Future<void> _splitRefreshTail = Future<void>.value();
+
List<Transaction> get transactions =>
UnmodifiableListView(_transactions.map((t) => t.toTransaction()));
@@ -118,7 +137,11 @@ class TransactionsProvider with ChangeNotifier {
_log.debug('TransactionsProvider',
'Online: $isOnline, ForceSync: $forceSync, LocalEmpty: ${localTransactions.isEmpty}');
- if (isOnline && (forceSync || localTransactions.isEmpty)) {
+ final needsResync = accountId == null
+ ? _accountsNeedingResync.isNotEmpty
+ : _accountsNeedingResync.contains(accountId);
+ if (isOnline &&
+ (forceSync || needsResync || localTransactions.isEmpty)) {
_log.debug(
'TransactionsProvider',
'Syncing transactions from server${accountId != null ? " with account filter" : ""}',
@@ -131,6 +154,12 @@ class TransactionsProvider with ChangeNotifier {
if (result.success) {
_log.info('TransactionsProvider',
'Sync successful, synced ${result.syncedCount} transactions');
+ await _dropDestroyedSplitChildren();
+ if (accountId == null) {
+ _accountsNeedingResync.clear();
+ } else {
+ _accountsNeedingResync.remove(accountId);
+ }
// Reload from local storage after sync
final updatedTransactions = await _offlineStorage.getTransactions(
accountId: accountId,
@@ -362,6 +391,56 @@ class TransactionsProvider with ChangeNotifier {
}
}
+ /// Refresh the cache after a split was created, replaced or removed on the
+ /// server. Children the server destroyed are dropped locally (now and after
+ /// every later sync), because an account-scoped sync only upserts and would
+ /// leave them behind. Refreshes are serialized, and an account whose
+ /// refresh could not sync is synced again on its next fetch.
+ Future<void> refreshAfterSplitChange({
+ required String accessToken,
+ required String accountId,
+ List<String> removedChildIds = const [],
+ }) {
+ _destroyedSplitChildIds.addAll(removedChildIds);
+ _accountsNeedingResync.add(accountId);
+ final run = _splitRefreshTail.catchError((Object _) {}).then(
+ (_) => _refreshAfterSplitChange(
+ accessToken: accessToken,
+ accountId: accountId,
+ ),
+ );
+ _splitRefreshTail = run;
+ return run;
+ }
+
+ Future<void> _refreshAfterSplitChange({
+ required String accessToken,
+ required String accountId,
+ }) async {
+ if (_isDisposed) return;
+ await _dropDestroyedSplitChildren();
+ await fetchTransactions(
+ accessToken: accessToken,
+ accountId: accountId,
+ forceSync: true,
+ );
+ }
+
+ /// Removes every known-destroyed split child from local storage. Each id is
+ /// handled on its own, so one failure does not leave the rest behind.
+ Future<void> _dropDestroyedSplitChildren() async {
+ for (final id in _destroyedSplitChildIds.toList()) {
+ try {
+ await _offlineStorage.deleteTransactionByServerId(id);
+ } catch (e) {
+ _log.error(
+ 'TransactionsProvider',
+ 'Failed to drop a removed split child with ${e.runtimeType}',
+ );
+ }
+ }
+ }
+
/// Delete a transaction
Future<bool> deleteTransaction({
required String accessToken,
@@ -545,6 +624,7 @@ class TransactionsProvider with ChangeNotifier {
void clearTransactions() {
_transactions = [];
+ _accountsNeedingResync.clear();
_error = null;
notifyListeners();
}
diff --git a/mobile/lib/screens/calendar_screen.dart b/mobile/lib/screens/calendar_screen.dart
index 0742789707..568ffb3ffb 100644
--- a/mobile/lib/screens/calendar_screen.dart
+++ b/mobile/lib/screens/calendar_screen.dart
@@ -4,6 +4,7 @@ import 'package:intl/intl.dart';
import '../models/account.dart';
import '../models/transaction.dart';
import '../providers/accounts_provider.dart';
+import '../providers/transaction_splits_provider.dart';
import '../providers/transactions_provider.dart';
import '../providers/auth_provider.dart';
import '../providers/privacy_provider.dart';
@@ -115,7 +116,19 @@ class _CalendarScreenState extends State<CalendarScreen> {
_log.debug('CalendarScreen',
'Starting to calculate daily changes for ${transactions.length} transactions');
+ // A split parent's amount is carried by its children, which are cached
+ // too, so counting both doubles the day. The index flags split parents
+ // (`split_parent`); servers without the flag fall back to the splits this
+ // device knows about.
+ final splits = Provider.of<TransactionSplitsProvider?>(
+ context,
+ listen: false,
+ );
+
for (var transaction in transactions) {
+ final id = transaction.id;
+ if (transaction.splitParent == true) continue;
+ if (id != null && splits != null && splits.isSplitParent(id)) continue;
try {
final date = DateTime.parse(transaction.date);
final dateKey = DateFormat('yyyy-MM-dd').format(date);
diff --git a/mobile/lib/screens/settings_screen.dart b/mobile/lib/screens/settings_screen.dart
index 4306e7dc2c..d5fab9f65b 100644
--- a/mobile/lib/screens/settings_screen.dart
+++ b/mobile/lib/screens/settings_screen.dart
@@ -7,6 +7,7 @@ import '../providers/auth_provider.dart';
import '../providers/categories_provider.dart';
import '../providers/merchants_provider.dart';
import '../providers/tags_provider.dart';
+import '../providers/transaction_splits_provider.dart';
import '../providers/theme_provider.dart';
import '../providers/privacy_provider.dart';
import '../services/offline_storage_service.dart';
@@ -250,6 +251,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
Provider.of<CategoriesProvider>(context, listen: false).clear();
Provider.of<MerchantsProvider>(context, listen: false).clear();
Provider.of<TagsProvider>(context, listen: false).clear();
+ Provider.of<TransactionSplitsProvider>(context, listen: false)
+ .clear();
}
log.info('Settings', 'Local data cleared successfully');
@@ -342,6 +345,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
Provider.of<CategoriesProvider>(context, listen: false).clear();
Provider.of<MerchantsProvider>(context, listen: false).clear();
Provider.of<TagsProvider>(context, listen: false).clear();
+ Provider.of<TransactionSplitsProvider>(context, listen: false)
+ .clear();
}
if (!context.mounted) return;
diff --git a/mobile/lib/screens/transaction_edit_screen.dart b/mobile/lib/screens/transaction_edit_screen.dart
index 97da47f6ae..b2945079a0 100644
--- a/mobile/lib/screens/transaction_edit_screen.dart
+++ b/mobile/lib/screens/transaction_edit_screen.dart
@@ -8,7 +8,9 @@ import '../providers/auth_provider.dart';
import '../providers/categories_provider.dart';
import '../providers/merchants_provider.dart';
import '../providers/tags_provider.dart';
+import '../providers/transaction_splits_provider.dart';
import '../providers/transactions_provider.dart';
+import '../widgets/transaction_split_section.dart';
import '../l10n/app_localizations.dart';
class TransactionEditScreen extends StatefulWidget {
@@ -79,9 +81,16 @@ class _TransactionEditScreenState extends State<TransactionEditScreen> {
Future<void> _save() async {
final l = AppLocalizations.of(context);
- if (!_formKey.currentState!.validate() || widget.transaction.id == null) {
+ final id = widget.transaction.id;
+ if (!_formKey.currentState!.validate() || id == null) {
return;
}
+ // Re-check: the API rejects direct edits to split children.
+ final splits = Provider.of<TransactionSplitsProvider>(
+ context,
+ listen: false,
+ );
+ if (!splits.canEditAfterLookup(id) || splits.isSplitChild(id)) return;
setState(() {
_isSaving = true;
@@ -317,8 +326,20 @@ class _TransactionEditScreenState extends State<TransactionEditScreen> {
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
- final canEdit = widget.transaction.id != null &&
+ final transactionId = widget.transaction.id;
+ // Split children are owned by their parent's split: the API rejects direct
+ // edits to them, so only the split editor can change them. The transaction
+ // index omits split membership, so the form stays locked until the split
+ // lookup below has confirmed this is not a split child.
+ final splits = context.watch<TransactionSplitsProvider>();
+ final isSplitChild =
+ transactionId != null && splits.isSplitChild(transactionId);
+ final isSynced = transactionId != null &&
widget.transaction.syncStatus == SyncStatus.synced;
+ final splitStatusPending = transactionId != null &&
+ isSynced &&
+ !splits.canEditAfterLookup(transactionId);
+ final canEdit = isSynced && !splitStatusPending && !isSplitChild;
final l = AppLocalizations.of(context);
@@ -329,7 +350,16 @@ class _TransactionEditScreenState extends State<TransactionEditScreen> {
child: ListView(
padding: const EdgeInsets.all(16),
children: [
- if (!canEdit) ...[
+ if (isSplitChild) ...[
+ SplitNoticeBanner(
+ text: l.splitChildEditLocked,
+ icon: Icons.lock_outline,
+ ),
+ const SizedBox(height: 16),
+ ] else if (splitStatusPending) ...[
+ SplitNoticeBanner(text: l.splitStatusUnknownLocked),
+ const SizedBox(height: 16),
+ ] else if (!isSynced) ...[
Card(
color: colorScheme.errorContainer,
child: Padding(
@@ -420,6 +450,15 @@ class _TransactionEditScreenState extends State<TransactionEditScreen> {
: const Icon(Icons.save),
label: Text(_isSaving ? l.transactionEditSaving : l.commonSave),
),
+ const SizedBox(height: 24),
+ TransactionSplitSection(
+ transaction: widget.transaction,
+ // After a split write the list behind this screen is reloading;
+ // close when this transaction itself was replaced or removed.
+ onChanged: (removed) {
+ if (removed && mounted) Navigator.pop(context, true);
+ },
+ ),
],
),
),
diff --git a/mobile/lib/screens/transaction_split_screen.dart b/mobile/lib/screens/transaction_split_screen.dart
new file mode 100644
index 0000000000..b9c6df9e1c
--- /dev/null
+++ b/mobile/lib/screens/transaction_split_screen.dart
@@ -0,0 +1,619 @@
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+
+import '../l10n/app_localizations.dart';
+import '../models/category.dart' as models;
+import '../models/transaction_split.dart';
+import '../providers/auth_provider.dart';
+import '../providers/categories_provider.dart';
+import '../providers/privacy_provider.dart';
+import '../providers/transaction_splits_provider.dart';
+import '../providers/transactions_provider.dart';
+import '../theme/sure_colors.dart';
+import '../theme/sure_spacing.dart';
+import '../theme/sure_tokens.dart';
+import '../utils/money_masker.dart';
+import '../utils/split_math.dart';
+import '../widgets/money_text.dart';
+import '../widgets/sure_button.dart';
+import '../widgets/sure_card.dart';
+import '../widgets/sure_text_field.dart';
+import '../widgets/transaction_split_section.dart' show SplitNoticeBanner;
+
+/// The transaction being split, reduced to what the editor needs.
+class SplitEditorTarget {
+ /// Server id of the split parent (or the transaction about to be split).
+ final String transactionId;
+ final String accountId;
+ final String name;
+ final String date;
+ final String currency;
+ final String? categoryId;
+
+ /// Exact parent amount in [SplitMath.scale] units, API sign convention
+ /// (expenses positive, income negative).
+ final BigInt amountUnits;
+
+ const SplitEditorTarget({
+ required this.transactionId,
+ required this.accountId,
+ required this.name,
+ required this.date,
+ required this.currency,
+ required this.amountUnits,
+ this.categoryId,
+ });
+
+ /// +1 for expenses (positive stored amounts), -1 for income.
+ BigInt get sign => amountUnits.isNegative ? BigInt.from(-1) : BigInt.one;
+
+ /// The total the rows must add up to, as the user sees it (always >= 0).
+ BigInt get totalMagnitude => amountUnits.abs();
+}
+
+class _SplitRow {
+ _SplitRow({String name = '', String amount = '', this.categoryId})
+ : nameController = TextEditingController(text: name),
+ amountController = TextEditingController(text: amount);
+
+ final Key key = UniqueKey();
+ final TextEditingController nameController;
+ final TextEditingController amountController;
+ String? categoryId;
+
+ /// Carried over from an existing child so a replace does not silently
+ /// re-include an entry the user excluded on the web.
+ bool excluded = false;
+
+ void dispose() {
+ nameController.dispose();
+ amountController.dispose();
+ }
+}
+
+/// Create or edit a transaction split: one row per child with a name, amount
+/// and category, a live "remaining" indicator, and a save that is only enabled
+/// once the rows add up exactly to the original amount. Mirrors the web
+/// split editor (`app/views/splits/new|edit.html.erb`).
+///
+/// Row amounts are entered as magnitudes in the same direction as the original
+/// transaction; a minus sign marks a part that goes the other way.
+class TransactionSplitScreen extends StatefulWidget {
+ final SplitEditorTarget target;
+
+ /// The current split when editing; null when creating a new one.
+ final TransactionSplit? existing;
+
+ const TransactionSplitScreen({
+ super.key,
+ required this.target,
+ this.existing,
+ });
+
+ @override
+ State<TransactionSplitScreen> createState() => _TransactionSplitScreenState();
+}
+
+class _TransactionSplitScreenState extends State<TransactionSplitScreen> {
+ static const _maxNameLength = 255;
+
+ final _formKey = GlobalKey<FormState>();
+ final List<_SplitRow> _rows = [];
+ bool _isSaving = false;
+
+ SplitEditorTarget get _target => widget.target;
+ bool get _isEditing => widget.existing != null;
+ int get _decimals => SplitMath.inputDecimals(
+ _target.currency,
+ _target.amountUnits,
+ childUnits:
+ widget.existing?.children.map((c) => c.amountUnits) ?? const [],
+ );
+
+ @override
+ void initState() {
+ super.initState();
+ final existing = widget.existing;
+ if (existing != null && existing.children.isNotEmpty) {
+ for (final child in existing.children) {
+ final magnitude = child.amountUnits * _target.sign;
+ _rows.add(
+ _SplitRow(
+ name: child.name,
+ amount: SplitMath.toDecimalString(magnitude, decimals: _decimals),
+ categoryId: child.categoryId,
+ )..excluded = child.excluded,
+ );
+ }
+ } else {
+ _rows
+ ..add(_SplitRow(name: _target.name, categoryId: _target.categoryId))
+ ..add(_SplitRow());
+ }
+ WidgetsBinding.instance.addPostFrameCallback((_) => _loadCategories());
+ }
+
+ @override
+ void dispose() {
+ for (final row in _rows) {
+ row.dispose();
+ }
+ super.dispose();
+ }
+
+ Future<void> _loadCategories() async {
+ final authProvider = Provider.of<AuthProvider>(context, listen: false);
+ final categoriesProvider = Provider.of<CategoriesProvider>(
+ context,
+ listen: false,
+ );
+ try {
+ final accessToken = await authProvider.getValidAccessToken();
+ if (accessToken == null || !mounted) return;
+ await categoriesProvider.fetchCategories(accessToken: accessToken);
+ } catch (_) {
+ // CategoriesProvider exposes its own error state.
+ }
+ }
+
+ String? get _locale => Localizations.maybeLocaleOf(context)?.toString();
+
+ BigInt get _remaining => SplitMath.remaining(
+ _target.totalMagnitude,
+ _rows.map((row) => row.amountController.text),
+ locale: _locale,
+ );
+
+ /// Amount errors are shown as the user types, so they gate Save. A missing
+ /// name does not: tapping Save runs the form validators, which put the
+ /// "name required" error on the row instead of leaving Save disabled
+ /// without a reason.
+ bool get _rowsValid => _rows.every(
+ (row) =>
+ SplitMath.validateAmount(
+ row.amountController.text,
+ decimals: _decimals,
+ locale: _locale,
+ ) ==
+ null,
+ );
+
+ void _addRow() {
+ setState(() => _rows.add(_SplitRow()));
+ }
+
+ void _removeRow(_SplitRow row) {
+ if (_rows.length <= 1) return;
+ setState(() => _rows.remove(row));
+ row.dispose();
+ }
+
+ String? _validateName(String? value) {
+ final l = AppLocalizations.of(context);
+ final text = value?.trim() ?? '';
+ if (text.isEmpty) return l.splitEditorNameRequired;
+ if (text.length > _maxNameLength) {
+ return l.transactionEditNameMaxLength(_maxNameLength);
+ }
+ return null;
+ }
+
+ String? _validateAmount(String? value) {
+ final l = AppLocalizations.of(context);
+ switch (SplitMath.validateAmount(
+ value ?? '',
+ decimals: _decimals,
+ locale: _locale,
+ )) {
+ case SplitAmountError.required:
+ return l.splitEditorAmountRequired;
+ case SplitAmountError.invalid:
+ return l.splitEditorAmountInvalid;
+ case SplitAmountError.zero:
+ return l.splitEditorAmountZero;
+ case SplitAmountError.tooPrecise:
+ return l.splitEditorAmountTooPrecise(_decimals);
+ case null:
+ return null;
+ }
+ }
+
+ Future<void> _save() async {
+ final l = AppLocalizations.of(context);
+ if (!_formKey.currentState!.validate() ||
+ _remaining != BigInt.zero ||
+ _isSaving) {
+ return;
+ }
+
+ final authProvider = Provider.of<AuthProvider>(context, listen: false);
+ final splitsProvider = Provider.of<TransactionSplitsProvider>(
+ context,
+ listen: false,
+ );
+ final transactionsProvider = Provider.of<TransactionsProvider>(
+ context,
+ listen: false,
+ );
+ final messenger = ScaffoldMessenger.of(context);
+ final palette = SureColors.of(context).palette;
+
+ final rows = _rows.map((row) {
+ final units =
+ SplitMath.parseUserInput(row.amountController.text, locale: _locale)!;
+ return SplitRowInput(
+ name: row.nameController.text.trim(),
+ amount: SplitMath.toDecimalString(units * _target.sign),
+ categoryId: row.categoryId,
+ excluded: row.excluded,
+ );
+ }).toList();
+
+ setState(() => _isSaving = true);
+
+ final accessToken = await authProvider.getValidAccessToken();
+ if (accessToken == null) {
+ if (!mounted) return;
+ setState(() => _isSaving = false);
+ messenger.showSnackBar(
+ SnackBar(
+ content: Text(l.transactionEditSessionExpired),
+ backgroundColor: palette.destructive,
+ ),
+ );
+ return;
+ }
+
+ final result = await splitsProvider.saveSplit(
+ accessToken: accessToken,
+ transactionId: _target.transactionId,
+ rows: rows,
+ replace: _isEditing,
+ );
+
+ if (!mounted) return;
+
+ if (!result.success) {
+ setState(() => _isSaving = false);
+ final message = result.error == TransactionSplitsProvider.offlineError
+ ? l.splitEditorOffline
+ : (result.error ?? l.splitEditorSaveFailed);
+ messenger.showSnackBar(
+ SnackBar(content: Text(message), backgroundColor: palette.destructive),
+ );
+ return;
+ }
+
+ // The list reload runs in the background; the editor can close now.
+ transactionsProvider.refreshAfterSplitChange(
+ accessToken: accessToken,
+ accountId: _target.accountId,
+ removedChildIds: result.removedChildIds,
+ );
+
+ messenger.showSnackBar(
+ SnackBar(
+ content: Text(_isEditing ? l.splitEditorUpdated : l.splitEditorSaved),
+ backgroundColor: palette.success,
+ ),
+ );
+ Navigator.pop(context, true);
+ }
+
+ List<DropdownMenuItem<String?>> _categoryItems(
+ List<models.Category> categories,
+ _SplitRow row,
+ ) {
+ final l = AppLocalizations.of(context);
+ final items = <DropdownMenuItem<String?>>[
+ DropdownMenuItem<String?>(
+ value: null,
+ child: Text(l.splitUncategorized),
+ ),
+ ];
+
+ final hasCurrent = row.categoryId == null ||
+ categories.any((category) => category.id == row.categoryId);
+ if (!hasCurrent) {
+ items.add(
+ DropdownMenuItem<String?>(
+ value: row.categoryId,
+ child: Text(l.transactionEditCurrentCategory),
+ ),
+ );
+ }
+
+ items.addAll(
+ categories.map(
+ (category) => DropdownMenuItem<String?>(
+ value: category.id,
+ child: Text(category.displayName, overflow: TextOverflow.ellipsis),
+ ),
+ ),
+ );
+ return items;
+ }
+
+ String _money(BigInt units, {required bool hidden}) {
+ return MoneyMasker.mask(
+ SplitMath.formatMoney(
+ units,
+ _target.currency,
+ decimals: _decimals,
+ locale: _locale,
+ ),
+ hidden: hidden,
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final l = AppLocalizations.of(context);
+ final theme = Theme.of(context);
+ final palette = SureColors.of(context).palette;
+ final hidden = context.watch<PrivacyProvider>().hidden;
+ final isOnline = context.watch<TransactionSplitsProvider>().isOnline;
+
+ final remaining = _remaining;
+ final balanced = remaining == BigInt.zero;
+ final canSave = isOnline && !_isSaving && balanced && _rowsValid;
+
+ return Scaffold(
+ appBar: AppBar(
+ title:
+ Text(_isEditing ? l.splitEditorEditTitle : l.splitEditorNewTitle),
+ ),
+ body: Form(
+ key: _formKey,
+ child: ListView(
+ padding: const EdgeInsets.all(SureSpacing.xl),
+ children: [
+ if (!isOnline) ...[
+ SplitNoticeBanner(
+ text: l.splitEditorOffline,
+ icon: Icons.cloud_off,
+ ),
+ const SizedBox(height: SureSpacing.lg),
+ ],
+ SureCard(
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ _target.name,
+ style: theme.textTheme.titleMedium?.copyWith(
+ fontWeight: SureTokens.weightSemibold,
+ color: palette.textPrimary,
+ ),
+ ),
+ const SizedBox(height: SureSpacing.xs),
+ Text(
+ _target.date,
+ style: theme.textTheme.bodySmall?.copyWith(
+ color: palette.textSecondary,
+ ),
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(width: SureSpacing.lg),
+ Column(
+ crossAxisAlignment: CrossAxisAlignment.end,
+ children: [
+ Text(
+ l.splitEditorOriginalAmount,
+ style: theme.textTheme.labelSmall?.copyWith(
+ color: palette.textSecondary,
+ ),
+ ),
+ const SizedBox(height: SureSpacing.xs),
+ Text(
+ _money(_target.totalMagnitude, hidden: hidden),
+ key: const Key('split-original-amount'),
+ style: SureMoney.tabular(
+ theme.textTheme.titleMedium?.copyWith(
+ fontWeight: SureTokens.weightSemibold,
+ color: palette.textPrimary,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(height: SureSpacing.lg),
+ Text(
+ l.splitEditorAmountHelper,
+ style: theme.textTheme.bodySmall?.copyWith(
+ color: palette.textSecondary,
+ ),
+ ),
+ const SizedBox(height: SureSpacing.lg),
+ for (var i = 0; i < _rows.length; i++) ...[
+ _buildRow(i, _rows[i], hidden: hidden),
+ const SizedBox(height: SureSpacing.lg),
+ ],
+ SureButton(
+ key: const Key('split-add-row'),
+ label: l.splitEditorAddRow,
+ variant: SureButtonVariant.outline,
+ leading: const Icon(Icons.add, size: 18),
+ fullWidth: true,
+ onPressed: _isSaving ? null : _addRow,
+ ),
+ const SizedBox(height: SureSpacing.lg),
+ _RemainingIndicator(
+ label: l.splitEditorRemaining,
+ amount: _money(remaining, hidden: hidden),
+ balanced: balanced,
+ message: balanced ? null : l.splitEditorAmountsMustMatch,
+ ),
+ const SizedBox(height: SureSpacing.xxxl),
+ SureButton(
+ key: const Key('split-save'),
+ label:
+ _isEditing ? l.splitEditorSubmitEdit : l.splitEditorSubmitNew,
+ fullWidth: true,
+ size: SureButtonSize.lg,
+ loading: _isSaving,
+ onPressed: canSave ? _save : null,
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _buildRow(int index, _SplitRow row, {required bool hidden}) {
+ final l = AppLocalizations.of(context);
+ final theme = Theme.of(context);
+ final palette = SureColors.of(context).palette;
+
+ return SureCard(
+ key: row.key,
+ elevated: false,
+ padding: const EdgeInsets.all(SureSpacing.lg),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ children: [
+ Expanded(
+ child: Text(
+ l.splitEditorRowLabel(index + 1),
+ style: theme.textTheme.labelMedium?.copyWith(
+ color: palette.textSecondary,
+ fontWeight: SureTokens.weightMedium,
+ ),
+ ),
+ ),
+ if (_rows.length > 1)
+ IconButton(
+ key: Key('split-remove-row-$index'),
+ icon: const Icon(Icons.close, size: 18),
+ tooltip: l.splitEditorRemoveRow,
+ visualDensity: VisualDensity.compact,
+ onPressed: _isSaving ? null : () => _removeRow(row),
+ ),
+ ],
+ ),
+ const SizedBox(height: SureSpacing.md),
+ SureTextField(
+ key: Key('split-name-$index'),
+ controller: row.nameController,
+ label: l.splitEditorNameLabel,
+ hint: l.splitEditorNamePlaceholder,
+ enabled: !_isSaving,
+ validator: _validateName,
+ autovalidateMode: AutovalidateMode.onUserInteraction,
+ onChanged: (_) => setState(() {}),
+ ),
+ const SizedBox(height: SureSpacing.md),
+ SureTextField(
+ key: Key('split-amount-$index'),
+ controller: row.amountController,
+ label: l.splitEditorAmountLabel,
+ hint: SplitMath.toDecimalString(BigInt.zero, decimals: _decimals),
+ enabled: !_isSaving,
+ obscureText: hidden,
+ keyboardType: const TextInputType.numberWithOptions(
+ decimal: true,
+ signed: true,
+ ),
+ validator: _validateAmount,
+ autovalidateMode: AutovalidateMode.onUserInteraction,
+ onChanged: (_) => setState(() {}),
+ ),
+ const SizedBox(height: SureSpacing.md),
+ Consumer<CategoriesProvider>(
+ builder: (context, categoriesProvider, _) {
+ return DropdownButtonFormField<String?>(
+ key: Key('split-category-$index'),
+ value: row.categoryId,
+ isExpanded: true,
+ decoration: InputDecoration(
+ labelText: l.splitEditorCategoryLabel,
+ ),
+ items: _categoryItems(categoriesProvider.categories, row),
+ onChanged: _isSaving
+ ? null
+ : (value) => setState(() => row.categoryId = value),
+ );
+ },
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+class _RemainingIndicator extends StatelessWidget {
+ const _RemainingIndicator({
+ required this.label,
+ required this.amount,
+ required this.balanced,
+ this.message,
+ });
+
+ final String label;
+ final String amount;
+ final bool balanced;
+ final String? message;
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ final palette = SureColors.of(context).palette;
+ final tone = balanced ? palette.success : palette.destructive;
+
+ return Container(
+ key: const Key('split-remaining'),
+ padding: const EdgeInsets.all(SureSpacing.lg),
+ decoration: BoxDecoration(
+ color: tone.withValues(alpha: 0.08),
+ borderRadius: BorderRadius.circular(SureTokens.radiusLg),
+ border: Border.all(color: tone.withValues(alpha: 0.5)),
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ children: [
+ Expanded(
+ child: Text(
+ label,
+ style: theme.textTheme.bodyMedium?.copyWith(
+ color: palette.textSecondary,
+ fontWeight: SureTokens.weightMedium,
+ ),
+ ),
+ ),
+ Text(
+ amount,
+ key: const Key('split-remaining-amount'),
+ style: SureMoney.tabular(
+ theme.textTheme.bodyMedium?.copyWith(
+ color: tone,
+ fontWeight: SureTokens.weightSemibold,
+ ),
+ ),
+ ),
+ ],
+ ),
+ if (message != null) ...[
+ const SizedBox(height: SureSpacing.sm),
+ Text(
+ message!,
+ style: theme.textTheme.bodySmall?.copyWith(color: tone),
+ ),
+ ],
+ ],
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/screens/transactions_list_screen.dart b/mobile/lib/screens/transactions_list_screen.dart
index 1aa156345e..966629a5c8 100644
--- a/mobile/lib/screens/transactions_list_screen.dart
+++ b/mobile/lib/screens/transactions_list_screen.dart
@@ -1,3 +1,5 @@
+import 'dart:async';
+
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/account.dart';
@@ -5,6 +7,7 @@ import '../models/transaction.dart';
import '../models/offline_transaction.dart';
import '../providers/auth_provider.dart';
import '../providers/categories_provider.dart';
+import '../providers/transaction_splits_provider.dart';
import '../providers/transactions_provider.dart';
import '../screens/transaction_edit_screen.dart';
import '../screens/transaction_form_screen.dart';
@@ -16,7 +19,9 @@ import '../theme/sure_tokens.dart';
import '../providers/privacy_provider.dart';
import '../utils/amount_parser.dart';
import '../utils/money_masker.dart';
+import '../utils/split_list_grouping.dart';
import '../widgets/money_text.dart';
+import '../widgets/transaction_split_section.dart' show SplitBadge;
import '../l10n/app_localizations.dart';
class TransactionsListScreen extends StatefulWidget {
@@ -132,6 +137,30 @@ class _TransactionsListScreenState extends State<TransactionsListScreen> {
accessToken: accessToken,
accountId: widget.account.id,
);
+ if (!mounted) return;
+
+ // The index flags split parents, so only those need a split lookup to
+ // group their children under them; other rows cost no extra request.
+ final splits =
+ Provider.of<TransactionSplitsProvider>(context, listen: false);
+ unawaited(splits.loadFlaggedParents(
+ accessToken: accessToken,
+ transactionIds: [
+ for (final t in transactionsProvider.offlineTransactions)
+ if (t.splitParent == true && t.id != null) t.id!,
+ ],
+ ));
+ }
+
+ /// Ids of cached rows the transactions index flags as split parents.
+ Set<String> _flaggedSplitParents() {
+ final transactions =
+ Provider.of<TransactionsProvider>(context, listen: false)
+ .offlineTransactions;
+ return {
+ for (final t in transactions)
+ if (t.splitParent == true && t.id != null) t.id!,
+ };
}
void _toggleSelectionMode() {
@@ -143,12 +172,102 @@ class _TransactionsListScreenState extends State<TransactionsListScreen> {
});
}
- void _toggleTransactionSelection(String transactionId) {
+ /// Split parents and children can't be deleted like plain transactions: the
+ /// server refuses a child, and deleting a parent cascades to its children,
+ /// which this list would keep showing. Point the user at "Unsplit" instead.
+ ///
+ /// Rows the index flags as split parents are blocked straight away, even
+ /// offline. Split children carry no flag, so every other row is checked
+ /// with [TransactionSplitsProvider.checkBeforeDelete], and a lookup that
+ /// fails while online blocks the delete.
+ Future<bool> _blockSplitDelete(
+ String? transactionId, {
+ bool fresh = false,
+ }) async {
+ if (transactionId == null) return false;
+ return _blockSplitDeletes([transactionId], fresh: fresh);
+ }
+
+ /// Checks every id in [transactionIds] and returns true (after telling the
+ /// user why) when any of them must not be deleted. Split rows are dropped
+ /// from the selection, since they can never be bulk-deleted.
+ Future<bool> _blockSplitDeletes(
+ List<String> transactionIds, {
+ bool fresh = false,
+ }) async {
+ if (transactionIds.isEmpty) return false;
+ final splits =
+ Provider.of<TransactionSplitsProvider>(context, listen: false);
+ final auth = Provider.of<AuthProvider>(context, listen: false);
+ final flagged = _flaggedSplitParents();
+ final token = splits.isOnline ? await auth.getValidAccessToken() : null;
+ if (!mounted) return true;
+
+ final statuses = await Future.wait(
+ transactionIds.map(
+ (id) => flagged.contains(id)
+ ? Future.value(SplitDeleteStatus.split)
+ : splits.checkBeforeDelete(
+ accessToken: token,
+ transactionId: id,
+ fresh: fresh,
+ ),
+ ),
+ );
+ if (!mounted) return true;
+
+ final splitIds = <String>[
+ for (var i = 0; i < transactionIds.length; i++)
+ if (statuses[i] == SplitDeleteStatus.split) transactionIds[i],
+ ];
+ final anyUnknown = statuses.contains(SplitDeleteStatus.unknown);
+ if (splitIds.isEmpty && !anyUnknown) return false;
+
+ final l = AppLocalizations.of(context);
+ if (splitIds.isNotEmpty && _selectedTransactions.any(splitIds.contains)) {
+ setState(() => _selectedTransactions.removeAll(splitIds));
+ }
+ ScaffoldMessenger.of(context).showSnackBar(
+ SnackBar(
+ content: Text(
+ splitIds.isNotEmpty
+ ? l.transactionsListSplitDeleteBlocked
+ : l.transactionsListSplitStatusUnknown,
+ ),
+ ),
+ );
+ return true;
+ }
+
+ /// Rows whose split lookup is in flight; a repeat tap on one is ignored so a
+ /// double tap can't select and then deselect it.
+ final Set<String> _selectionLookups = {};
+
+ Future<void> _toggleTransactionSelection(String transactionId) async {
+ if (_selectionLookups.contains(transactionId)) return;
+ // Decide select or deselect before the lookup, so the outcome doesn't
+ // depend on the state after the await.
+ final selecting = !_selectedTransactions.contains(transactionId);
+ if (selecting) {
+ // Selecting is for deleting, so check against the server now; the delete
+ // re-checks only rows still unconfirmed (selected offline, say), which
+ // keeps a bulk delete from issuing one lookup per row twice.
+ _selectionLookups.add(transactionId);
+ final bool blocked;
+ try {
+ blocked = await _blockSplitDelete(transactionId, fresh: true);
+ } finally {
+ _selectionLookups.remove(transactionId);
+ }
+ if (blocked) return;
+ }
+ // The lookup can take a round trip; the user may have left selection mode.
+ if (!mounted || (selecting && !_isSelectionMode)) return;
setState(() {
- if (_selectedTransactions.contains(transactionId)) {
- _selectedTransactions.remove(transactionId);
- } else {
+ if (selecting) {
_selectedTransactions.add(transactionId);
+ } else {
+ _selectedTransactions.remove(transactionId);
}
});
}
@@ -181,6 +300,13 @@ class _TransactionsListScreenState extends State<TransactionsListScreen> {
if (confirmed != true || !mounted) return;
+ // Re-check at delete time: a row selected offline (or whose lookup has
+ // not succeeded) is looked up now, and known splits are refused.
+ if (await _blockSplitDeletes(_selectedTransactions.toList())) {
+ return;
+ }
+ if (!mounted || _selectedTransactions.isEmpty) return;
+
final count = _selectedTransactions.length;
final authProvider = Provider.of<AuthProvider>(context, listen: false);
final transactionsProvider = Provider.of<TransactionsProvider>(context, listen: false);
@@ -285,6 +411,8 @@ class _TransactionsListScreenState extends State<TransactionsListScreen> {
Future<bool> _confirmAndDeleteTransaction(Transaction transaction) async {
if (transaction.id == null) return false;
+ if (await _blockSplitDelete(transaction.id, fresh: true)) return false;
+ if (!mounted) return false;
// Show confirmation dialog
// Capture providers and localizations before async gap
@@ -468,6 +596,22 @@ class _TransactionsListScreenState extends State<TransactionsListScreen> {
}
final transactions = _getFilteredTransactions(allTransactions);
+ // Group known split children under their parent, like the web list.
+ final splits = context.watch<TransactionSplitsProvider>();
+ final flaggedParents = {
+ for (final t in transactions)
+ if (t.splitParent == true && t.id != null) t.id!,
+ };
+ final entries = groupSplitEntries<OfflineTransaction>(
+ transactions,
+ idOf: (t) => t.id,
+ childIdsOf: (id) => splitChildIdsForList(
+ id,
+ splits: splits,
+ flaggedParents: flaggedParents,
+ ),
+ parentIdOf: splits.parentIdFor,
+ );
return RefreshIndicator(
onRefresh: _loadTransactions,
@@ -510,9 +654,12 @@ class _TransactionsListScreenState extends State<TransactionsListScreen> {
)
: ListView.builder(
padding: const EdgeInsets.all(16),
- itemCount: transactions.length,
+ itemCount: entries.length,
itemBuilder: (context, index) {
- final transaction = transactions[index];
+ final entry = entries[index];
+ final transaction = entry.item;
+ final isSplitParent = entry.role == SplitRole.parent;
+ final isSplitChild = entry.role == SplitRole.child;
final isSelected = transaction.id != null &&
_selectedTransactions.contains(transaction.id);
final isPending = transaction.syncStatus == SyncStatus.pending;
@@ -543,9 +690,13 @@ class _TransactionsListScreenState extends State<TransactionsListScreen> {
),
confirmDismiss: (direction) => _confirmAndDeleteTransaction(transaction),
child: Opacity(
- opacity: hasPendingStatus ? 0.5 : 1.0,
+ // Split parents are dimmed: their children carry the amounts.
+ opacity: hasPendingStatus || isSplitParent ? 0.5 : 1.0,
child: Card(
- margin: const EdgeInsets.only(bottom: 12),
+ margin: EdgeInsets.only(
+ bottom: 12,
+ left: entry.grouped ? 24 : 0,
+ ),
child: InkWell(
onTap: _isSelectionMode && transaction.id != null
? () => _toggleTransactionSelection(transaction.id!)
@@ -593,6 +744,17 @@ class _TransactionsListScreenState extends State<TransactionsListScreen> {
overflow: TextOverflow.ellipsis,
),
),
+ if (isSplitParent) ...[
+ const SizedBox(width: 8),
+ SplitBadge(label: l.splitBadge),
+ ] else if (isSplitChild && !entry.grouped) ...[
+ const SizedBox(width: 4),
+ Icon(
+ Icons.call_split,
+ size: 14,
+ color: colorScheme.onSurfaceVariant,
+ ),
+ ],
if (transaction.categoryName != null) ...[
const SizedBox(width: 8),
Flexible(
diff --git a/mobile/lib/services/database_helper.dart b/mobile/lib/services/database_helper.dart
index 93a01848d9..97d372d615 100644
--- a/mobile/lib/services/database_helper.dart
+++ b/mobile/lib/services/database_helper.dart
@@ -72,7 +72,7 @@ class DatabaseHelper {
return await openDatabase(
path,
- version: 3,
+ version: 4,
onCreate: _createDB,
onUpgrade: _upgradeDB,
);
@@ -118,6 +118,10 @@ class DatabaseHelper {
merchant_name TEXT,
tag_ids TEXT DEFAULT '[]',
tag_names TEXT DEFAULT '[]',
+ amount_decimal TEXT,
+ kind TEXT,
+ excluded INTEGER,
+ split_parent INTEGER,
sync_status TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
@@ -213,6 +217,24 @@ class DatabaseHelper {
"ALTER TABLE transactions ADD COLUMN tag_names TEXT DEFAULT '[]'");
}
}
+ if (oldVersion < 4) {
+ // Exact amount, kind and split/excluded flags from the transactions
+ // index. Rows cached before this stay null until the next sync.
+ final columns = await db.rawQuery('PRAGMA table_info(transactions)');
+ final columnNames = columns.map((c) => c['name'] as String).toSet();
+ const added = {
+ 'amount_decimal': 'TEXT',
+ 'kind': 'TEXT',
+ 'excluded': 'INTEGER',
+ 'split_parent': 'INTEGER',
+ };
+ for (final column in added.entries) {
+ if (!columnNames.contains(column.key)) {
+ await db.execute(
+ 'ALTER TABLE transactions ADD COLUMN ${column.key} ${column.value}');
+ }
+ }
+ }
}
// Transaction CRUD operations
diff --git a/mobile/lib/services/offline_storage_service.dart b/mobile/lib/services/offline_storage_service.dart
index bf2fc3cb8d..26a4fe886e 100644
--- a/mobile/lib/services/offline_storage_service.dart
+++ b/mobile/lib/services/offline_storage_service.dart
@@ -299,6 +299,10 @@ class OfflineStorageService {
merchantName: transaction.merchantName,
tagIds: transaction.tagIds,
tagNames: transaction.tagNames,
+ amountDecimal: transaction.amountDecimal,
+ kind: transaction.kind,
+ excluded: transaction.excluded,
+ splitParent: transaction.splitParent,
syncStatus: SyncStatus.synced,
);
await _dbHelper.insertTransaction(offlineTransaction.toDatabaseMap());
diff --git a/mobile/lib/services/transaction_splits_service.dart b/mobile/lib/services/transaction_splits_service.dart
new file mode 100644
index 0000000000..f0b8b955a9
--- /dev/null
+++ b/mobile/lib/services/transaction_splits_service.dart
@@ -0,0 +1,175 @@
+import 'dart:convert';
+
+import 'package:http/http.dart' as http;
+
+import '../models/transaction_split.dart';
+import 'api_config.dart';
+import 'transactions_service.dart';
+
+/// HTTP client for `/api/v1/transactions/:id/split`.
+///
+/// Addressing a split child resolves to its parent server-side, so any id in
+/// the split can be passed as [transactionId].
+class TransactionSplitsService {
+ final http.Client _client;
+
+ /// Deadline for each request, response body included.
+ final Duration _timeout;
+
+ TransactionSplitsService({
+ http.Client? client,
+ Duration timeout = const Duration(seconds: 30),
+ }) : _client = client ?? http.Client(),
+ _timeout = timeout;
+
+ Uri _url(String transactionId) => Uri.parse(
+ '${ApiConfig.baseUrl}/api/v1/transactions/'
+ '${Uri.encodeComponent(transactionId)}/split',
+ );
+
+ Map<String, String> _headers(String accessToken) => {
+ ...ApiConfig.getAuthHeaders(accessToken),
+ 'Content-Type': 'application/json',
+ };
+
+ /// Returns `{'success': true, 'split': TransactionSplit?}`. The server's
+ /// "Transaction is not split" 404 means `split` is null rather than an
+ /// error. Any other 404 (the transaction was deleted or is not visible to
+ /// this user) is a failure, so it is never cached as a confirmed unsplit.
+ Future<Map<String, dynamic>> getSplit({
+ required String accessToken,
+ required String transactionId,
+ }) async {
+ try {
+ final response = await _client
+ .get(_url(transactionId), headers: _headers(accessToken))
+ .timeout(_timeout);
+
+ if (response.statusCode == 200) {
+ return {
+ 'success': true,
+ 'split': TransactionSplit.fromJson(
+ jsonDecode(response.body) as Map<String, dynamic>,
+ ),
+ };
+ }
+ if (response.statusCode == 404 && _isNotSplitResponse(response.body)) {
+ return {'success': true, 'split': null};
+ }
+ return _failure(response, 'Failed to load split');
+ } catch (e) {
+ return {'success': false, 'error': 'Network error: ${e.toString()}'};
+ }
+ }
+
+ /// Splits an unsplit transaction (POST).
+ Future<Map<String, dynamic>> createSplit({
+ required String accessToken,
+ required String transactionId,
+ required List<SplitRowInput> rows,
+ }) {
+ return _write(
+ method: 'POST',
+ accessToken: accessToken,
+ transactionId: transactionId,
+ rows: rows,
+ fallback: 'Failed to split transaction',
+ );
+ }
+
+ /// Replaces every child of an existing split (PATCH).
+ Future<Map<String, dynamic>> updateSplit({
+ required String accessToken,
+ required String transactionId,
+ required List<SplitRowInput> rows,
+ }) {
+ return _write(
+ method: 'PATCH',
+ accessToken: accessToken,
+ transactionId: transactionId,
+ rows: rows,
+ fallback: 'Failed to update split',
+ );
+ }
+
+ /// Removes the split and restores the parent (DELETE).
+ Future<Map<String, dynamic>> deleteSplit({
+ required String accessToken,
+ required String transactionId,
+ }) async {
+ try {
+ final response = await _client
+ .delete(_url(transactionId), headers: _headers(accessToken))
+ .timeout(_timeout);
+
+ if (response.statusCode == 204 || response.statusCode == 200) {
+ return {'success': true};
+ }
+ return _failure(response, 'Failed to unsplit transaction');
+ } catch (e) {
+ return {'success': false, 'error': 'Network error: ${e.toString()}'};
+ }
+ }
+
+ Future<Map<String, dynamic>> _write({
+ required String method,
+ required String accessToken,
+ required String transactionId,
+ required List<SplitRowInput> rows,
+ required String fallback,
+ }) async {
+ final body = jsonEncode({
+ 'split': {'splits': rows.map((row) => row.toJson()).toList()},
+ });
+
+ try {
+ final request = http.Request(method, _url(transactionId))
+ ..headers.addAll(_headers(accessToken))
+ ..body = body;
+ // One deadline for the headers and the body: a stream that stalls after
+ // the headers would otherwise leave the save pending forever.
+ final response = await _client
+ .send(request)
+ .then(http.Response.fromStream)
+ .timeout(_timeout);
+
+ if (response.statusCode == 200 || response.statusCode == 201) {
+ return {
+ 'success': true,
+ 'split': TransactionSplit.fromJson(
+ jsonDecode(response.body) as Map<String, dynamic>,
+ ),
+ };
+ }
+ return _failure(response, fallback);
+ } catch (e) {
+ return {'success': false, 'error': 'Network error: ${e.toString()}'};
+ }
+ }
+
+ /// Api::V1::SplitsController#show answers an unsplit transaction with
+ /// `{"error": "not_found", "message": "Transaction is not split"}`. A
+ /// missing or inaccessible transaction is also a `not_found` 404 (message
+ /// "Transaction not found"), so only the message tells the two apart.
+ static bool _isNotSplitResponse(String body) {
+ try {
+ final payload = jsonDecode(body);
+ return payload is Map && payload['message'] == 'Transaction is not split';
+ } on FormatException {
+ return false;
+ }
+ }
+
+ Map<String, dynamic> _failure(http.Response response, String fallback) {
+ if (response.statusCode == 401) {
+ return {'success': false, 'error': 'unauthorized'};
+ }
+ return {
+ 'success': false,
+ 'error': TransactionsService.errorMessageFromResponseBody(
+ response.body,
+ fallback: fallback,
+ ),
+ };
+ }
+}
diff --git a/mobile/lib/utils/split_list_grouping.dart b/mobile/lib/utils/split_list_grouping.dart
new file mode 100644
index 0000000000..461ae3ca67
--- /dev/null
+++ b/mobile/lib/utils/split_list_grouping.dart
@@ -0,0 +1,102 @@
+/// Where a transaction sits in a split, for list rendering.
+enum SplitRole {
+ /// Not part of any split the app knows about.
+ none,
+
+ /// A split parent (rendered dimmed with a "Split" badge, like the web).
+ parent,
+
+ /// A split child.
+ child,
+}
+
+class SplitListEntry<T> {
+ final T item;
+ final SplitRole role;
+
+ /// True when a child is rendered directly under its parent.
+ final bool grouped;
+
+ const SplitListEntry(this.item, this.role, {this.grouped = false});
+}
+
+/// Reorders [items] so each known split parent is followed by its children,
+/// mirroring the web's grouped split view (`group_split_entries`). Children
+/// whose parent is not in [items] stay where they are, marked as children.
+/// Anything the lookups do not know about passes through unchanged.
+List<SplitListEntry<T>> groupSplitEntries<T>(
+ List<T> items, {
+ required String? Function(T item) idOf,
+ required List<String>? Function(String id) childIdsOf,
+ required String? Function(String id) parentIdOf,
+}) {
+ final byId = <String, T>{};
+ for (final item in items) {
+ final id = idOf(item);
+ if (id != null) byId[id] = item;
+ }
+
+ final result = <SplitListEntry<T>>[];
+ final placed = <String>{};
+
+ for (final item in items) {
+ final id = idOf(item);
+ if (id == null) {
+ result.add(SplitListEntry(item, SplitRole.none));
+ continue;
+ }
+ if (placed.contains(id)) continue;
+
+ final childIds = childIdsOf(id);
+ if (childIds != null) {
+ placed.add(id);
+ result.add(SplitListEntry(item, SplitRole.parent));
+ for (final childId in childIds) {
+ final child = byId[childId];
+ if (child == null || placed.contains(childId)) continue;
+ placed.add(childId);
+ result.add(SplitListEntry(child, SplitRole.child, grouped: true));
+ }
+ continue;
+ }
+
+ final parentId = parentIdOf(id);
+ if (parentId != null && byId.containsKey(parentId)) {
+ // Rendered under its parent when the parent comes up.
+ continue;
+ }
+
+ placed.add(id);
+ result.add(
+ SplitListEntry(
+ item,
+ parentId != null ? SplitRole.child : SplitRole.none,
+ ),
+ );
+ }
+
+ return result;
+}
+
+/// Child ids for [groupSplitEntries]' `childIdsOf`, combining the split
+/// lookups this device made with the index's `split_parent` flag.
+///
+/// A looked-up split wins, since it is fresher than the cached flag. A row
+/// only flagged as a parent is still rendered as one, with no children
+/// grouped under it until its lookup lands.
+List<String>? splitChildIdsForList(
+ String id, {
+ required SplitLookup splits,
+ required Set<String> flaggedParents,
+}) {
+ if (splits.isSplitParent(id)) return splits.childIdsFor(id) ?? const [];
+ if (splits.isSplitStatusKnown(id)) return null;
+ return flaggedParents.contains(id) ? const [] : null;
+}
+
+/// What [splitChildIdsForList] needs from the split lookups.
+abstract class SplitLookup {
+ bool isSplitParent(String transactionId);
+ bool isSplitStatusKnown(String transactionId);
+ List<String>? childIdsFor(String parentId);
+}
diff --git a/mobile/lib/utils/split_math.dart b/mobile/lib/utils/split_math.dart
new file mode 100644
index 0000000000..efe87d21fe
--- /dev/null
+++ b/mobile/lib/utils/split_math.dart
@@ -0,0 +1,260 @@
+import 'package:intl/intl.dart';
+
+import 'amount_parser.dart';
+
+/// Why a split row amount was rejected.
+enum SplitAmountError { required, invalid, zero, tooPrecise }
+
+/// Exact decimal arithmetic for transaction splits.
+///
+/// The server stores amounts as `decimal(19,4)` and `split!` requires the
+/// children to sum *exactly* to the parent, so floating point is not good
+/// enough here (0.1 + 0.2 != 0.3). Amounts are held as [BigInt] counts of
+/// 1/10^[scale] units instead.
+class SplitMath {
+ const SplitMath._();
+
+ /// Matches the API's `AMOUNT_SCALE` (`entries.amount` is decimal(19,4)).
+ static const int scale = 4;
+
+ static final BigInt _unit = BigInt.from(10).pow(scale);
+
+ /// Number of minor-unit digits for [currency] (2 for USD/EUR, 0 for JPY,
+ /// 3 for KWD), falling back to 2 for unknown codes.
+ static int currencyDecimals(String currency) {
+ if (currency.trim().isEmpty) return 2;
+ try {
+ return NumberFormat.currency(name: currency.toUpperCase())
+ .decimalDigits ??
+ 2;
+ } catch (_) {
+ return 2;
+ }
+ }
+
+ /// Parses a plain decimal string (`"12.5"`, `"-0.3333"`, `"1.5e2"`) into
+ /// scaled units. Returns null when [input] is not a number or carries more
+ /// than [scale] significant decimal places.
+ static BigInt? parseUnits(String input) {
+ var text = input.trim();
+ if (text.isEmpty) return null;
+
+ var exponent = 0;
+ final expMatch = RegExp(r'^(.*?)[eE]([+-]?\d+)$').firstMatch(text);
+ if (expMatch != null) {
+ text = expMatch.group(1)!;
+ exponent = int.parse(expMatch.group(2)!);
+ }
+
+ final match = RegExp(r'^([+-])?(\d*)(?:\.(\d*))?$').firstMatch(text);
+ if (match == null) return null;
+
+ final negative = match.group(1) == '-';
+ final intPart = match.group(2) ?? '';
+ var fracPart = match.group(3) ?? '';
+ if (intPart.isEmpty && fracPart.isEmpty) return null;
+
+ var digits = '$intPart$fracPart';
+ var decimals = fracPart.length - exponent;
+ if (decimals < 0) {
+ digits = digits + '0' * -decimals;
+ decimals = 0;
+ }
+
+ // Drop trailing zeros beyond the supported scale ("1.50000" is fine).
+ while (decimals > scale && digits.endsWith('0')) {
+ digits = digits.substring(0, digits.length - 1);
+ decimals--;
+ }
+ if (decimals > scale) return null;
+
+ digits = digits + '0' * (scale - decimals);
+ final value = BigInt.parse(digits.isEmpty ? '0' : digits);
+ return negative ? -value : value;
+ }
+
+ /// Parses user input typed in the app's locale (e.g. `"1 234,56"` in
+ /// Swedish) into scaled units. Locale separator handling is delegated to
+ /// [AmountParser]; input with anything but digits, separators, spaces and
+ /// a sign is rejected (AmountParser alone would silently drop letters).
+ /// Returns null when the input is not a plain number.
+ static BigInt? parseUserInput(String input, {String? locale}) {
+ final text = input.trim();
+ if (text.isEmpty) return null;
+ if (RegExp(r'[^0-9.,+\-\u2212\u2012\u2013\u2014\s\u00A0\u202F]')
+ .hasMatch(text)) {
+ return null;
+ }
+ final signMatches =
+ RegExp(r'[+\-\u2212\u2012\u2013\u2014]').allMatches(text).toList();
+ if (signMatches.length > 1 ||
+ (signMatches.isNotEmpty && signMatches.first.start != 0)) {
+ return null;
+ }
+ try {
+ final canonical = AmountParser.canonicalize(text, locale: locale);
+ if (!RegExp(r'^[+-]?(\d+\.?\d*|\.\d+)$').hasMatch(canonical)) {
+ return null;
+ }
+ return parseUnits(canonical);
+ } on FormatException {
+ return null;
+ }
+ }
+
+ /// Number of decimal places actually used by [units] (0..[scale]).
+ static int decimalsUsed(BigInt units) {
+ var abs = units.abs();
+ var used = scale;
+ final ten = BigInt.from(10);
+ while (used > 0 && abs % ten == BigInt.zero) {
+ abs = abs ~/ ten;
+ used--;
+ }
+ return used;
+ }
+
+ /// Decimal places a split row may use: the currency's precision, widened
+ /// only when the stored parent amount itself carries finer precision (so
+ /// the rows can still add up to it exactly), or when an existing child
+ /// ([childUnits]) already needs finer precision than the parent.
+ static int inputDecimals(
+ String currency,
+ BigInt parentUnits, {
+ Iterable<BigInt> childUnits = const [],
+ }) {
+ var digits = currencyDecimals(currency);
+ final parentDigits = decimalsUsed(parentUnits);
+ if (parentDigits > digits) digits = parentDigits;
+ for (final units in childUnits) {
+ final used = decimalsUsed(units);
+ if (used > digits) digits = used;
+ }
+ return digits > scale ? scale : digits;
+ }
+
+ /// Whether [units] can be expressed with [decimals] decimal places.
+ static bool fitsDecimals(BigInt units, int decimals) {
+ if (decimals >= scale) return true;
+ final step = BigInt.from(10).pow(scale - decimals);
+ return units % step == BigInt.zero;
+ }
+
+ /// Formats scaled units as a plain decimal string with exactly [decimals]
+ /// places (or more, if needed to stay exact). Suitable for the API.
+ static String toDecimalString(BigInt units, {int? decimals}) {
+ final negative = units.isNegative;
+ final abs = units.abs();
+ final whole = abs ~/ _unit;
+ var frac = (abs % _unit).toString().padLeft(scale, '0');
+
+ var keep = decimals ?? scale;
+ final needed = decimalsUsed(abs);
+ if (needed > keep) keep = needed;
+ frac = frac.substring(0, keep);
+
+ final body = keep == 0 ? '$whole' : '$whole.$frac';
+ return negative && abs != BigInt.zero ? '-$body' : body;
+ }
+
+ /// Formats [units] as money in [currency] using [decimals] places (more if
+ /// needed to stay exact).
+ ///
+ /// The digits come from the exact decimal units, never from a double:
+ /// decimal(19,4) holds amounts a double cannot represent exactly. The
+ /// locale's currency format supplies the symbol, sign placement, grouping
+ /// and decimal separator.
+ static String formatMoney(
+ BigInt units,
+ String currency, {
+ required int decimals,
+ String? locale,
+ }) {
+ final exact = toDecimalString(units.abs(), decimals: decimals);
+ try {
+ final format = NumberFormat.simpleCurrency(
+ locale: locale,
+ name: currency.isEmpty ? null : currency.toUpperCase(),
+ decimalDigits: 0,
+ );
+ final dot = exact.indexOf('.');
+ final whole = BigInt.parse(dot < 0 ? exact : exact.substring(0, dot));
+ final fraction = dot < 0 ? '' : exact.substring(dot + 1);
+
+ // Grouped integer digits, e.g. "1,234,567" (localized digits too).
+ final grouped = _digitRun(format.format(whole.toInt()), format);
+ // A one-digit template carries the symbol and sign placement.
+ final template = format.format(units.isNegative ? -1 : 1);
+ final one = String.fromCharCode(
+ format.symbols.ZERO_DIGIT.codeUnitAt(0) + 1,
+ );
+ final at = template.indexOf(one);
+ if (grouped == null || at < 0 || whole.bitLength > 62) {
+ throw const FormatException('unexpected currency pattern');
+ }
+ final number = fraction.isEmpty
+ ? grouped
+ : '$grouped${format.symbols.DECIMAL_SEP}'
+ '${_localizeDigits(fraction, format)}';
+ return template.replaceRange(at, at + 1, number);
+ } catch (_) {
+ final text = units.isNegative ? '-$exact' : exact;
+ return currency.isEmpty ? text : '$text $currency';
+ }
+ }
+
+ /// The span of [formatted] from its first to its last digit, keeping the
+ /// grouping separators between them.
+ static String? _digitRun(String formatted, NumberFormat format) {
+ final zero = format.symbols.ZERO_DIGIT.codeUnitAt(0);
+ bool isDigit(int c) => c >= zero && c <= zero + 9;
+ var first = -1;
+ var last = -1;
+ for (var i = 0; i < formatted.length; i++) {
+ if (isDigit(formatted.codeUnitAt(i))) {
+ if (first < 0) first = i;
+ last = i;
+ }
+ }
+ return first < 0 ? null : formatted.substring(first, last + 1);
+ }
+
+ static String _localizeDigits(String asciiDigits, NumberFormat format) {
+ final zero = format.symbols.ZERO_DIGIT.codeUnitAt(0);
+ if (zero == 0x30) return asciiDigits;
+ return String.fromCharCodes(
+ asciiDigits.codeUnits.map((c) => c - 0x30 + zero),
+ );
+ }
+
+ /// Validates one row's typed amount. Returns null when it is acceptable.
+ static SplitAmountError? validateAmount(
+ String input, {
+ required int decimals,
+ String? locale,
+ }) {
+ if (input.trim().isEmpty) return SplitAmountError.required;
+ final units = parseUserInput(input, locale: locale);
+ if (units == null) {
+ // More than [scale] places parses as null too; report it as precision.
+ final widened = RegExp(r'^[+-]?\d*[.,]\d{5,}$').hasMatch(input.trim());
+ return widened ? SplitAmountError.tooPrecise : SplitAmountError.invalid;
+ }
+ if (units == BigInt.zero) return SplitAmountError.zero;
+ if (!fitsDecimals(units, decimals)) return SplitAmountError.tooPrecise;
+ return null;
+ }
+
+ /// What is left to allocate: [total] minus every parseable row amount.
+ static BigInt remaining(
+ BigInt total,
+ Iterable<String> rowInputs, {
+ String? locale,
+ }) {
+ var sum = BigInt.zero;
+ for (final input in rowInputs) {
+ sum += parseUserInput(input, locale: locale) ?? BigInt.zero;
+ }
+ return total - sum;
+ }
+}
diff --git a/mobile/lib/widgets/transaction_split_section.dart b/mobile/lib/widgets/transaction_split_section.dart
new file mode 100644
index 0000000000..738844b7a0
--- /dev/null
+++ b/mobile/lib/widgets/transaction_split_section.dart
@@ -0,0 +1,653 @@
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+
+import '../l10n/app_localizations.dart';
+import '../models/offline_transaction.dart';
+import '../models/transaction.dart';
+import '../models/transaction_split.dart';
+import '../providers/auth_provider.dart';
+import '../providers/categories_provider.dart';
+import '../providers/privacy_provider.dart';
+import '../providers/transaction_splits_provider.dart';
+import '../providers/transactions_provider.dart';
+import '../screens/transaction_split_screen.dart';
+import '../theme/sure_colors.dart';
+import '../theme/sure_spacing.dart';
+import '../theme/sure_tokens.dart';
+import '../utils/amount_parser.dart';
+import '../utils/money_masker.dart';
+import '../utils/split_math.dart';
+import 'money_text.dart';
+import 'sure_button.dart';
+import 'sure_card.dart';
+
+/// Split details for the transaction detail/edit screen, mirroring the web
+/// transaction drawer:
+/// - a split parent lists its children with "Edit split" and "Unsplit";
+/// - a split child says it is part of a split and links to the same actions;
+/// - any other synced transaction offers "Split transaction".
+///
+/// Splits need the server, so everything here is read-only (or hidden) while
+/// offline. [onChanged] fires after a successful write with `true` when the
+/// transaction this screen shows no longer exists (a child of a split that
+/// was replaced or removed).
+
+/// The amount a new split of [transaction] must sum to, in [SplitMath] units
+/// and the API's sign convention (positive = outflow).
+///
+/// Uses the exact stored `amount_decimal` when the server sends it, so a
+/// `100.1250` USD entry splits to exactly 100.1250. Older servers only send
+/// the display amount, which is parsed instead (rounded to the currency).
+@visibleForTesting
+BigInt? splitTargetUnitsFor(Transaction transaction) {
+ final exact = transaction.amountDecimal;
+ if (exact != null) {
+ final units = SplitMath.parseUnits(exact);
+ if (units != null) return units;
+ }
+ try {
+ final parsed = AmountParser.parse(transaction.amount);
+ final magnitude =
+ SplitMath.parseUnits(parsed.canonicalValue.replaceFirst('-', ''));
+ if (magnitude == null) return null;
+ return transaction.isIncome ? -magnitude : magnitude;
+ } on FormatException {
+ return null;
+ }
+}
+
+class TransactionSplitSection extends StatefulWidget {
+ const TransactionSplitSection({
+ super.key,
+ required this.transaction,
+ this.onChanged,
+ });
+
+ final OfflineTransaction transaction;
+ final ValueChanged<bool>? onChanged;
+
+ @override
+ State<TransactionSplitSection> createState() =>
+ _TransactionSplitSectionState();
+}
+
+class _TransactionSplitSectionState extends State<TransactionSplitSection> {
+ bool _loaded = false;
+ bool _working = false;
+
+ TransactionSplitsProvider? _splits;
+
+ /// Set while offline, so the lookup is retried once the device reconnects.
+ bool _wasOffline = false;
+
+ String? get _id => widget.transaction.id;
+
+ bool get _isSynced =>
+ _id != null && widget.transaction.syncStatus == SyncStatus.synced;
+
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) => _load());
+ }
+
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ final splits = Provider.of<TransactionSplitsProvider>(
+ context,
+ listen: false,
+ );
+ if (!identical(splits, _splits)) {
+ _splits?.removeListener(_onSplitsChanged);
+ _splits = splits..addListener(_onSplitsChanged);
+ _wasOffline = !splits.isOnline;
+ }
+ }
+
+ @override
+ void dispose() {
+ _splits?.removeListener(_onSplitsChanged);
+ super.dispose();
+ }
+
+ /// Retries the lookup once the device comes back online, if it never
+ /// completed while offline.
+ void _onSplitsChanged() {
+ final splits = _splits;
+ if (splits == null || !mounted) return;
+ if (!splits.isOnline) {
+ _wasOffline = true;
+ } else if (_wasOffline) {
+ _wasOffline = false;
+ final id = _id;
+ if (_loaded && id != null && !splits.isSplitStatusKnown(id)) _load();
+ }
+ }
+
+ Future<void> _load() async {
+ if (!_isSynced || !mounted) return;
+ final authProvider = Provider.of<AuthProvider>(context, listen: false);
+ final splitsProvider = Provider.of<TransactionSplitsProvider>(
+ context,
+ listen: false,
+ );
+ final accessToken = await authProvider.getValidAccessToken();
+ if (!mounted) return;
+ if (accessToken == null) {
+ // No session: show the retry banner rather than a spinner.
+ setState(() => _loaded = true);
+ return;
+ }
+ await splitsProvider.loadSplit(
+ accessToken: accessToken,
+ transactionId: _id!,
+ );
+ if (mounted) setState(() => _loaded = true);
+ }
+
+ String? get _locale => Localizations.maybeLocaleOf(context)?.toString();
+
+ /// Editor target for a transaction that is not split yet. The list only has
+ /// the display-formatted amount, so the magnitude comes from that and the
+ /// sign from the classification; the server re-checks the exact sum.
+ SplitEditorTarget? _targetForUnsplit() {
+ final transaction = widget.transaction;
+ final units = splitTargetUnitsFor(transaction);
+ if (units == null) return null;
+ return SplitEditorTarget(
+ transactionId: _id!,
+ accountId: transaction.accountId,
+ name: transaction.name,
+ date: transaction.date,
+ currency: transaction.currency,
+ categoryId: transaction.categoryId,
+ amountUnits: units,
+ );
+ }
+
+ SplitEditorTarget _targetForSplit(TransactionSplit split) {
+ final transactions =
+ Provider.of<TransactionsProvider>(context, listen: false)
+ .offlineTransactions;
+ OfflineTransaction? parent;
+ for (final t in transactions) {
+ if (t.id == split.transactionId) {
+ parent = t;
+ break;
+ }
+ }
+ final isParent = split.transactionId == _id;
+ final source = parent ?? (isParent ? widget.transaction : null);
+
+ return SplitEditorTarget(
+ transactionId: split.transactionId,
+ accountId: widget.transaction.accountId,
+ name: source?.name ?? widget.transaction.name,
+ date: source?.date ?? widget.transaction.date,
+ currency: split.currency.isNotEmpty
+ ? split.currency
+ : widget.transaction.currency,
+ categoryId: source?.categoryId,
+ amountUnits: split.amountUnits,
+ );
+ }
+
+ Future<void> _openEditor({
+ required SplitEditorTarget target,
+ TransactionSplit? existing,
+ }) async {
+ final saved = await Navigator.push<bool>(
+ context,
+ MaterialPageRoute(
+ builder: (_) => TransactionSplitScreen(
+ target: target,
+ existing: existing,
+ ),
+ ),
+ );
+ if (saved == true && mounted) {
+ // A replace destroys and recreates every child, including this one.
+ widget.onChanged?.call(existing != null && existing.transactionId != _id);
+ }
+ }
+
+ Future<void> _confirmUnsplit(TransactionSplit split) async {
+ final l = AppLocalizations.of(context);
+ final palette = SureColors.of(context).palette;
+ final messenger = ScaffoldMessenger.of(context);
+ final authProvider = Provider.of<AuthProvider>(context, listen: false);
+ final splitsProvider = Provider.of<TransactionSplitsProvider>(
+ context,
+ listen: false,
+ );
+ final transactionsProvider = Provider.of<TransactionsProvider>(
+ context,
+ listen: false,
+ );
+
+ final confirmed = await showDialog<bool>(
+ context: context,
+ builder: (dialogContext) {
+ final dl = AppLocalizations.of(dialogContext);
+ return AlertDialog(
+ title: Text(dl.splitUnsplitTitle),
+ content: Text(dl.splitUnsplitConfirm),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(dialogContext, false),
+ child: Text(dl.commonCancel),
+ ),
+ TextButton(
+ onPressed: () => Navigator.pop(dialogContext, true),
+ style: TextButton.styleFrom(foregroundColor: palette.destructive),
+ child: Text(dl.splitUnsplitButton),
+ ),
+ ],
+ );
+ },
+ );
+ if (confirmed != true || !mounted) return;
+
+ setState(() => _working = true);
+ final accessToken = await authProvider.getValidAccessToken();
+ if (accessToken == null) {
+ if (mounted) setState(() => _working = false);
+ messenger.showSnackBar(
+ SnackBar(
+ content: Text(l.transactionEditSessionExpired),
+ backgroundColor: palette.destructive,
+ ),
+ );
+ return;
+ }
+
+ final result = await splitsProvider.unsplit(
+ accessToken: accessToken,
+ transactionId: split.transactionId,
+ );
+ if (!mounted) return;
+ setState(() => _working = false);
+
+ if (!result.success) {
+ final message = result.error == TransactionSplitsProvider.offlineError
+ ? l.splitEditorOffline
+ : (result.error ?? l.splitUnsplitFailed);
+ messenger.showSnackBar(
+ SnackBar(content: Text(message), backgroundColor: palette.destructive),
+ );
+ return;
+ }
+
+ transactionsProvider.refreshAfterSplitChange(
+ accessToken: accessToken,
+ accountId: widget.transaction.accountId,
+ removedChildIds: result.removedChildIds,
+ );
+ messenger.showSnackBar(
+ SnackBar(
+ content: Text(l.splitUnsplitSuccess),
+ backgroundColor: palette.success,
+ ),
+ );
+ widget.onChanged?.call(split.transactionId != _id);
+ }
+
+ String _childAmount(TransactionSplit split, TransactionSplitChild child,
+ {required bool hidden}) {
+ // Same direction as the parent reads as a plain amount; a part that goes
+ // the other way gets a minus sign, matching the editor's convention.
+ final sign = split.amountUnits.isNegative ? BigInt.from(-1) : BigInt.one;
+ final decimals = SplitMath.inputDecimals(
+ split.currency,
+ split.amountUnits,
+ childUnits: split.children.map((c) => c.amountUnits),
+ );
+ return MoneyMasker.mask(
+ SplitMath.formatMoney(
+ child.amountUnits * sign,
+ split.currency,
+ decimals: decimals,
+ locale: _locale,
+ ),
+ hidden: hidden,
+ );
+ }
+
+ String _categoryLabel(TransactionSplitChild child) {
+ final l = AppLocalizations.of(context);
+ final id = child.categoryId;
+ if (id == null) return child.categoryName ?? l.splitUncategorized;
+ for (final category in context.watch<CategoriesProvider>().categories) {
+ if (category.id == id) return category.displayName;
+ }
+ return child.categoryName ?? l.splitUncategorized;
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ if (!_isSynced) return const SizedBox.shrink();
+
+ final l = AppLocalizations.of(context);
+ final splitsProvider = context.watch<TransactionSplitsProvider>();
+ final hidden = context.watch<PrivacyProvider>().hidden;
+ final isOnline = splitsProvider.isOnline;
+ final split = splitsProvider.splitFor(_id!);
+ final loading = splitsProvider.isLoading(_id!) || (!_loaded && isOnline);
+
+ if (split == null) {
+ if (!isOnline) {
+ return SplitNoticeBanner(
+ text: l.splitOfflineNotice,
+ icon: Icons.cloud_off,
+ );
+ }
+ if (loading) {
+ return const Padding(
+ padding: EdgeInsets.all(SureSpacing.xl),
+ child: Center(child: CircularProgressIndicator()),
+ );
+ }
+ if (!splitsProvider.isSplitStatusKnown(_id!) && _loaded) {
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ SplitNoticeBanner(text: l.splitLoadFailed),
+ const SizedBox(height: SureSpacing.md),
+ Align(
+ alignment: Alignment.centerLeft,
+ child: SureButton(
+ key: const Key('split-retry'),
+ label: l.commonTryAgain,
+ variant: SureButtonVariant.outline,
+ size: SureButtonSize.sm,
+ leading: const Icon(Icons.refresh, size: 16),
+ onPressed: _load,
+ ),
+ ),
+ ],
+ );
+ }
+
+ final target = _targetForUnsplit();
+ return _SectionCard(
+ title: l.splitTransactionButton,
+ description: l.splitTransactionDescription,
+ actions: [
+ SureButton(
+ key: const Key('split-start'),
+ label: l.splitTransactionButton,
+ variant: SureButtonVariant.outline,
+ leading: const Icon(Icons.call_split, size: 18),
+ onPressed: target == null || _working
+ ? null
+ : () => _openEditor(target: target),
+ ),
+ ],
+ );
+ }
+
+ final isParent = split.transactionId == _id;
+ final actions = [
+ SureButton(
+ key: const Key('split-edit'),
+ label: l.splitEditButton,
+ variant: SureButtonVariant.outline,
+ size: SureButtonSize.sm,
+ leading: const Icon(Icons.edit_outlined, size: 16),
+ onPressed: isOnline && !_working
+ ? () => _openEditor(
+ target: _targetForSplit(split),
+ existing: split,
+ )
+ : null,
+ ),
+ SureButton(
+ key: const Key('split-unsplit'),
+ label: l.splitUnsplitButton,
+ variant: SureButtonVariant.ghost,
+ size: SureButtonSize.sm,
+ leading: const Icon(Icons.undo, size: 16),
+ loading: _working,
+ onPressed: isOnline && !_working ? () => _confirmUnsplit(split) : null,
+ ),
+ ];
+
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (!isOnline) ...[
+ SplitNoticeBanner(
+ text: l.splitOfflineNotice,
+ icon: Icons.cloud_off,
+ ),
+ const SizedBox(height: SureSpacing.lg),
+ ],
+ _SectionCard(
+ title: isParent ? l.splitSectionTitle : l.splitChildTitle,
+ description:
+ isParent ? l.splitSectionDescription : l.splitChildDescription,
+ actions: actions,
+ children: [
+ for (final child in split.children)
+ _ChildRow(
+ name: child.name,
+ category: _categoryLabel(child),
+ amount: _childAmount(split, child, hidden: hidden),
+ highlighted: child.id == _id,
+ ),
+ ],
+ ),
+ ],
+ );
+ }
+}
+
+class _SectionCard extends StatelessWidget {
+ const _SectionCard({
+ required this.title,
+ required this.description,
+ required this.actions,
+ this.children = const [],
+ });
+
+ final String title;
+ final String description;
+ final List<Widget> actions;
+ final List<Widget> children;
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ final palette = SureColors.of(context).palette;
+
+ return SureCard(
+ key: const Key('transaction-split-section'),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ children: [
+ Icon(Icons.call_split, size: 18, color: palette.textSecondary),
+ const SizedBox(width: SureSpacing.md),
+ Expanded(
+ child: Text(
+ title,
+ style: theme.textTheme.titleSmall?.copyWith(
+ color: palette.textPrimary,
+ fontWeight: SureTokens.weightSemibold,
+ ),
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: SureSpacing.sm),
+ Text(
+ description,
+ style: theme.textTheme.bodySmall?.copyWith(
+ color: palette.textSecondary,
+ ),
+ ),
+ if (children.isNotEmpty) ...[
+ const SizedBox(height: SureSpacing.lg),
+ for (final child in children) ...[
+ child,
+ const SizedBox(height: SureSpacing.md),
+ ],
+ ] else
+ const SizedBox(height: SureSpacing.lg),
+ Wrap(
+ spacing: SureSpacing.md,
+ runSpacing: SureSpacing.md,
+ children: actions,
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+class _ChildRow extends StatelessWidget {
+ const _ChildRow({
+ required this.name,
+ required this.category,
+ required this.amount,
+ this.highlighted = false,
+ });
+
+ final String name;
+ final String category;
+ final String amount;
+ final bool highlighted;
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ final palette = SureColors.of(context).palette;
+
+ return Container(
+ padding: const EdgeInsets.all(SureSpacing.lg),
+ decoration: BoxDecoration(
+ color: highlighted ? palette.containerInset : null,
+ borderRadius: BorderRadius.circular(SureTokens.radiusMd),
+ border: Border.all(color: palette.borderSecondary),
+ ),
+ child: Row(
+ children: [
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ name,
+ overflow: TextOverflow.ellipsis,
+ style: theme.textTheme.bodyMedium?.copyWith(
+ color: palette.textPrimary,
+ fontWeight: SureTokens.weightMedium,
+ ),
+ ),
+ const SizedBox(height: 2),
+ Text(
+ category,
+ overflow: TextOverflow.ellipsis,
+ style: theme.textTheme.bodySmall?.copyWith(
+ color: palette.textSecondary,
+ ),
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(width: SureSpacing.lg),
+ Text(
+ amount,
+ style: SureMoney.tabular(
+ theme.textTheme.bodyMedium?.copyWith(
+ color: palette.textPrimary,
+ fontWeight: SureTokens.weightMedium,
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+/// Small warning-toned banner used by the split UI. [icon] defaults to an
+/// info icon; offline notices pass [Icons.cloud_off].
+class SplitNoticeBanner extends StatelessWidget {
+ const SplitNoticeBanner({
+ super.key,
+ required this.text,
+ this.icon = Icons.info_outline,
+ });
+
+ final String text;
+ final IconData icon;
+
+ @override
+ Widget build(BuildContext context) {
+ final palette = SureColors.of(context).palette;
+ return Container(
+ padding: const EdgeInsets.all(SureSpacing.lg),
+ decoration: BoxDecoration(
+ color: palette.warning.withValues(alpha: 0.1),
+ borderRadius: BorderRadius.circular(SureTokens.radiusLg),
+ border: Border.all(color: palette.warning.withValues(alpha: 0.4)),
+ ),
+ child: Row(
+ children: [
+ Icon(icon, size: 18, color: palette.warning),
+ const SizedBox(width: SureSpacing.md),
+ Expanded(
+ child: Text(
+ text,
+ style: Theme.of(context)
+ .textTheme
+ .bodySmall
+ ?.copyWith(color: palette.textPrimary),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+/// "Split" pill shown on split parents in the transaction list, mirroring the
+/// web `DS::Pill` with the `split` icon.
+class SplitBadge extends StatelessWidget {
+ const SplitBadge({super.key, required this.label});
+
+ final String label;
+
+ @override
+ Widget build(BuildContext context) {
+ final palette = SureColors.of(context).palette;
+ return Container(
+ padding: const EdgeInsets.symmetric(
+ horizontal: SureSpacing.sm,
+ vertical: 2,
+ ),
+ decoration: BoxDecoration(
+ color: palette.containerInset,
+ borderRadius: BorderRadius.circular(999),
+ border: Border.all(color: palette.borderSecondary),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.call_split, size: 12, color: palette.textSecondary),
+ const SizedBox(width: 2),
+ Text(
+ label,
+ style: Theme.of(context).textTheme.labelSmall?.copyWith(
+ color: palette.textSecondary,
+ fontWeight: SureTokens.weightMedium,
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/mobile/test/models/transaction_index_fields_test.dart b/mobile/test/models/transaction_index_fields_test.dart
new file mode 100644
index 0000000000..200c4f8c77
--- /dev/null
+++ b/mobile/test/models/transaction_index_fields_test.dart
@@ -0,0 +1,317 @@
+import 'dart:convert';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:http/http.dart' as http;
+import 'package:http/testing.dart';
+import 'package:sure_mobile/models/offline_transaction.dart';
+import 'package:sure_mobile/models/transaction.dart';
+import 'package:sure_mobile/providers/transaction_splits_provider.dart';
+import 'package:sure_mobile/services/transaction_splits_service.dart';
+import 'package:sure_mobile/utils/split_list_grouping.dart';
+import 'package:sure_mobile/widgets/transaction_split_section.dart';
+
+Map<String, dynamic> _json({
+ String amount = r'$100.13',
+ String classification = 'expense',
+ Map<String, dynamic> extra = const {},
+}) =>
+ {
+ 'id': 'tx_1',
+ 'account': {'id': 'acct_1'},
+ 'name': 'Groceries',
+ 'date': '2026-06-01',
+ 'amount': amount,
+ 'currency': 'USD',
+ 'classification': classification,
+ ...extra,
+ };
+
+class _Lookups implements SplitLookup {
+ _Lookups({this.parents = const {}, this.known = const {}});
+
+ final Map<String, List<String>> parents;
+ final Set<String> known;
+
+ @override
+ List<String>? childIdsFor(String parentId) => parents[parentId];
+
+ @override
+ bool isSplitParent(String transactionId) =>
+ parents.containsKey(transactionId);
+
+ @override
+ bool isSplitStatusKnown(String transactionId) =>
+ known.contains(transactionId) || parents.containsKey(transactionId);
+}
+
+void main() {
+ group('Transaction index fields (#4422)', () {
+ test('parses amount_decimal, kind, excluded and split_parent', () {
+ final t = Transaction.fromJson(_json(extra: {
+ 'amount_decimal': '100.1250',
+ 'kind': 'loan_payment',
+ 'excluded': true,
+ 'split_parent': true,
+ }));
+
+ expect(t.amountDecimal, '100.1250');
+ expect(t.kind, 'loan_payment');
+ expect(t.excluded, isTrue);
+ expect(t.splitParent, isTrue);
+ });
+
+ test('leaves the fields null for servers that do not send them', () {
+ final t = Transaction.fromJson(_json());
+
+ expect(t.amountDecimal, isNull);
+ expect(t.kind, isNull);
+ expect(t.excluded, isNull);
+ expect(t.splitParent, isNull);
+ });
+
+ test('does not send the read-only fields back to the API', () {
+ final t = Transaction.fromJson(_json(extra: {
+ 'amount_decimal': '1.5',
+ 'kind': 'standard',
+ 'excluded': false,
+ 'split_parent': false,
+ }));
+
+ expect(
+ t.toJson().keys,
+ isNot(anyOf(contains('amount_decimal'), contains('kind'),
+ contains('excluded'), contains('split_parent'))),
+ );
+ });
+
+ test('round-trips through the offline database map', () {
+ final offline = OfflineTransaction.fromTransaction(
+ Transaction.fromJson(_json(extra: {
+ 'amount_decimal': '-40.5',
+ 'kind': 'standard',
+ 'excluded': true,
+ 'split_parent': true,
+ })),
+ localId: 'local_1',
+ );
+
+ final map = offline.toDatabaseMap();
+ expect(map['amount_decimal'], '-40.5');
+ expect(map['kind'], 'standard');
+ expect(map['excluded'], 1);
+ expect(map['split_parent'], 1);
+
+ final restored = OfflineTransaction.fromDatabaseMap(map);
+ expect(restored.amountDecimal, '-40.5');
+ expect(restored.kind, 'standard');
+ expect(restored.excluded, isTrue);
+ expect(restored.splitParent, isTrue);
+ expect(restored.toTransaction().splitParent, isTrue);
+ });
+
+ test('reads rows cached before the columns existed as unknown', () {
+ final map = OfflineTransaction.fromTransaction(
+ Transaction.fromJson(_json()),
+ localId: 'local_1',
+ ).toDatabaseMap()
+ ..remove('amount_decimal')
+ ..remove('kind')
+ ..remove('excluded')
+ ..remove('split_parent');
+
+ final restored = OfflineTransaction.fromDatabaseMap(map);
+ expect(restored.amountDecimal, isNull);
+ expect(restored.splitParent, isNull);
+ });
+
+ test('a server sync updates the split flag, e.g. after an unsplit', () {
+ final cached = OfflineTransaction.fromTransaction(
+ Transaction.fromJson(_json(extra: {
+ 'amount_decimal': '100.13',
+ 'split_parent': true,
+ 'excluded': true,
+ })),
+ localId: 'local_1',
+ );
+
+ final merged = cached.mergeServerTransaction(
+ Transaction.fromJson(_json(extra: {
+ 'amount_decimal': '100.13',
+ 'split_parent': false,
+ 'excluded': false,
+ })),
+ accountId: 'acct_1',
+ );
+
+ expect(merged.splitParent, isFalse);
+ expect(merged.excluded, isFalse);
+ });
+
+ test('a changed amount drops a stale exact amount', () {
+ final cached = OfflineTransaction.fromTransaction(
+ Transaction.fromJson(_json(extra: {'amount_decimal': '100.13'})),
+ localId: 'local_1',
+ );
+
+ // An older server sends no amount_decimal.
+ final merged = cached.mergeServerTransaction(
+ Transaction.fromJson(_json(amount: r'$90.00')),
+ accountId: 'acct_1',
+ );
+ expect(merged.amountDecimal, isNull);
+
+ expect(cached.copyWith(amount: r'$90.00').amountDecimal, isNull);
+ expect(cached.copyWith(name: 'Renamed').amountDecimal, '100.13');
+ });
+ });
+
+ group('splitTargetUnitsFor', () {
+ test('seeds a new split from the exact stored amount', () {
+ final t = Transaction.fromJson(_json(
+ amount: r'$12.35',
+ extra: {'amount_decimal': '12.3456'},
+ ));
+
+ // SplitMath units have 4 decimals: 12.3456, not the rounded 12.35.
+ expect(splitTargetUnitsFor(t), BigInt.from(123456));
+ });
+
+ test('keeps the API sign: a negative amount is an inflow', () {
+ final t = Transaction.fromJson(_json(
+ amount: r'$40.50',
+ classification: 'income',
+ extra: {'amount_decimal': '-40.5'},
+ ));
+
+ expect(splitTargetUnitsFor(t), BigInt.from(-405000));
+ });
+
+ test('falls back to the display amount on older servers', () {
+ final expense = Transaction.fromJson(_json(amount: r'$12.35'));
+ final income = Transaction.fromJson(
+ _json(amount: r'$40.50', classification: 'income'),
+ );
+
+ expect(splitTargetUnitsFor(expense), BigInt.from(123500));
+ expect(splitTargetUnitsFor(income), BigInt.from(-405000));
+ });
+ });
+
+ group('splitChildIdsForList', () {
+ test('a flagged parent is grouped as a parent before its lookup', () {
+ final ids = splitChildIdsForList(
+ 'p',
+ splits: _Lookups(),
+ flaggedParents: {'p'},
+ );
+ expect(ids, isEmpty);
+
+ final entries = groupSplitEntries<String>(
+ ['p', 'x'],
+ idOf: (id) => id,
+ childIdsOf: (id) => splitChildIdsForList(
+ id,
+ splits: _Lookups(),
+ flaggedParents: {'p'},
+ ),
+ parentIdOf: (_) => null,
+ );
+ expect(entries.first.role, SplitRole.parent);
+ expect(entries.last.role, SplitRole.none);
+ });
+
+ test('a looked-up split supplies the children', () {
+ final ids = splitChildIdsForList(
+ 'p',
+ splits: _Lookups(parents: {
+ 'p': ['c1', 'c2'],
+ }),
+ flaggedParents: const {},
+ );
+ expect(ids, ['c1', 'c2']);
+ });
+
+ test('a lookup that says "not split" wins over a stale flag', () {
+ final ids = splitChildIdsForList(
+ 'p',
+ splits: _Lookups(known: {'p'}),
+ flaggedParents: {'p'},
+ );
+ expect(ids, isNull);
+ });
+ });
+
+ group('TransactionSplitsProvider.loadFlaggedParents', () {
+ test('looks up flagged parents one at a time, up to the limit', () async {
+ final requested = <String>[];
+ var inFlight = 0;
+ var maxInFlight = 0;
+ final provider = TransactionSplitsProvider(
+ service: TransactionSplitsService(
+ client: MockClient((request) async {
+ inFlight++;
+ maxInFlight = inFlight > maxInFlight ? inFlight : maxInFlight;
+ requested.add(request.url.pathSegments.reversed.skip(1).first);
+ await Future<void>.delayed(Duration.zero);
+ inFlight--;
+ return http.Response(
+ jsonEncode({
+ 'error': 'not_found',
+ 'message': 'Transaction is not split',
+ }),
+ 404,
+ );
+ }),
+ ),
+ );
+
+ await provider.loadFlaggedParents(
+ accessToken: 'token',
+ transactionIds: ['a', 'b', 'c'],
+ limit: 2,
+ );
+
+ expect(requested, ['a', 'b']);
+ expect(maxInFlight, 1);
+ expect(provider.isSplitStatusKnown('a'), isTrue);
+
+ // Known rows are skipped on the next refresh.
+ await provider.loadFlaggedParents(
+ accessToken: 'token',
+ transactionIds: ['a', 'b', 'c'],
+ );
+ expect(requested, ['a', 'b', 'c']);
+ });
+
+ test('does not retry a flagged parent whose lookup failed', () async {
+ var calls = 0;
+ final provider = TransactionSplitsProvider(
+ service: TransactionSplitsService(
+ client: MockClient((request) async {
+ calls++;
+ return http.Response('oops', 500);
+ }),
+ ),
+ );
+
+ await provider.loadFlaggedParents(
+ accessToken: 'token',
+ transactionIds: ['a'],
+ );
+ await provider.loadFlaggedParents(
+ accessToken: 'token',
+ transactionIds: ['a'],
+ );
+
+ expect(calls, 1);
+ expect(provider.isSplitStatusKnown('a'), isFalse);
+
+ provider.clear();
+ await provider.loadFlaggedParents(
+ accessToken: 'token',
+ transactionIds: ['a'],
+ );
+ expect(calls, 2);
+ });
+ });
+}
diff --git a/mobile/test/providers/transactions_provider_split_refresh_test.dart b/mobile/test/providers/transactions_provider_split_refresh_test.dart
new file mode 100644
index 0000000000..970890d88b
--- /dev/null
+++ b/mobile/test/providers/transactions_provider_split_refresh_test.dart
@@ -0,0 +1,199 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:sure_mobile/models/offline_transaction.dart';
+import 'package:sure_mobile/providers/transactions_provider.dart';
+import 'package:sure_mobile/services/connectivity_service.dart';
+import 'package:sure_mobile/services/offline_storage_service.dart';
+import 'package:sure_mobile/services/sync_service.dart';
+
+/// Local cache keyed by server id; only what the split refresh touches.
+class _FakeStorage implements OfflineStorageService {
+ final Set<String> ids = {};
+ final Set<String> failingDeletes = {};
+
+ @override
+ Future<List<OfflineTransaction>> getTransactions({String? accountId}) async =>
+ [
+ for (final id in ids)
+ OfflineTransaction(
+ id: id,
+ localId: 'local_$id',
+ accountId: 'acct',
+ name: id,
+ date: '2026-06-01',
+ amount: r'$1.00',
+ currency: 'USD',
+ nature: 'expense',
+ syncStatus: SyncStatus.synced,
+ ),
+ ];
+
+ @override
+ Future<void> deleteTransactionByServerId(String serverId) async {
+ if (failingDeletes.contains(serverId)) {
+ throw StateError('disk error');
+ }
+ ids.remove(serverId);
+ }
+
+ @override
+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
+}
+
+/// Upserts whatever the "server" returns; each call can be held open.
+class _FakeSync implements SyncService {
+ _FakeSync(this.storage);
+
+ final _FakeStorage storage;
+ Set<String> serverIds = {};
+ bool succeed = true;
+ int calls = 0;
+ int inFlight = 0;
+ int maxInFlight = 0;
+ final List<Completer<void>> gates = [];
+
+ @override
+ Future<SyncResult> syncFromServer({
+ required String accessToken,
+ String? accountId,
+ }) async {
+ calls++;
+ inFlight++;
+ if (inFlight > maxInFlight) maxInFlight = inFlight;
+ // What the server returns is read when the request starts.
+ final snapshot = Set<String>.of(serverIds);
+ if (gates.isNotEmpty) await gates.removeAt(0).future;
+ inFlight--;
+ if (!succeed) return SyncResult(success: false, error: 'offline');
+ storage.ids.addAll(snapshot);
+ return SyncResult(success: true, syncedCount: snapshot.length);
+ }
+
+ @override
+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
+}
+
+class _Online extends ChangeNotifier implements ConnectivityService {
+ @override
+ bool get isOnline => true;
+
+ @override
+ bool get isOffline => false;
+
+ @override
+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
+}
+
+void main() {
+ late _FakeStorage storage;
+ late _FakeSync sync;
+ late TransactionsProvider provider;
+
+ setUp(() {
+ storage = _FakeStorage();
+ sync = _FakeSync(storage);
+ provider = TransactionsProvider(offlineStorage: storage, syncService: sync)
+ ..setConnectivityService(_Online());
+ });
+
+ test(
+ 'a sync that started before the split change cannot resurrect '
+ 'destroyed children', () async {
+ storage.ids.addAll({'parent', 'old_child_1', 'old_child_2'});
+ sync.serverIds = {'parent', 'old_child_1', 'old_child_2'};
+
+ // An earlier refresh fetched generation A and is still running.
+ final gate = Completer<void>();
+ sync.gates.add(gate);
+ final earlier = provider.fetchTransactions(
+ accessToken: 't',
+ accountId: 'acct',
+ forceSync: true,
+ );
+ await Future<void>.delayed(Duration.zero);
+
+ // The split is replaced on the server: A's children are gone.
+ sync.serverIds = {'parent', 'new_child_1', 'new_child_2'};
+ final refresh = provider.refreshAfterSplitChange(
+ accessToken: 't',
+ accountId: 'acct',
+ removedChildIds: const ['old_child_1', 'old_child_2'],
+ );
+
+ gate.complete(); // the stale response lands after the deletion
+ await earlier;
+ await refresh;
+
+ expect(storage.ids, {'parent', 'new_child_1', 'new_child_2'});
+ });
+
+ test('post-split refreshes run one at a time', () async {
+ final first = Completer<void>();
+ final second = Completer<void>();
+ sync.gates.addAll([first, second]);
+
+ final a = provider.refreshAfterSplitChange(
+ accessToken: 't',
+ accountId: 'acct',
+ removedChildIds: const ['c1'],
+ );
+ final b = provider.refreshAfterSplitChange(
+ accessToken: 't',
+ accountId: 'acct',
+ removedChildIds: const ['c2'],
+ );
+ await Future<void>.delayed(Duration.zero);
+ expect(sync.calls, 1);
+
+ first.complete();
+ await a;
+ second.complete();
+ await b;
+
+ expect(sync.calls, 2);
+ expect(sync.maxInFlight, 1);
+ });
+
+ test('one failed child delete does not keep the others cached', () async {
+ storage.ids.addAll({'c1', 'c2', 'c3'});
+ storage.failingDeletes.add('c1');
+
+ await provider.refreshAfterSplitChange(
+ accessToken: 't',
+ accountId: 'acct',
+ removedChildIds: const ['c1', 'c2', 'c3'],
+ );
+
+ expect(storage.ids, {'c1'});
+
+ // Retried after the next sync once the storage recovers.
+ storage.failingDeletes.clear();
+ await provider.fetchTransactions(
+ accessToken: 't',
+ accountId: 'acct',
+ forceSync: true,
+ );
+ expect(storage.ids, isEmpty);
+ });
+
+ test('a refresh that could not sync makes the next load sync', () async {
+ storage.ids.add('existing'); // non-empty cache: a plain load skips sync
+ sync.succeed = false;
+ await provider.refreshAfterSplitChange(
+ accessToken: 't',
+ accountId: 'acct',
+ removedChildIds: const ['c1'],
+ );
+ expect(sync.calls, 1);
+
+ sync.succeed = true;
+ await provider.fetchTransactions(accessToken: 't', accountId: 'acct');
+ expect(sync.calls, 2);
+
+ // Once it has synced, plain loads go back to the cache.
+ await provider.fetchTransactions(accessToken: 't', accountId: 'acct');
+ expect(sync.calls, 2);
+ });
+}
diff --git a/mobile/test/services/transaction_splits_service_test.dart b/mobile/test/services/transaction_splits_service_test.dart
new file mode 100644
index 0000000000..92d34b5227
--- /dev/null
+++ b/mobile/test/services/transaction_splits_service_test.dart
@@ -0,0 +1,243 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:http/http.dart' as http;
+import 'package:http/testing.dart';
+import 'package:sure_mobile/models/transaction_split.dart';
+import 'package:sure_mobile/services/transaction_splits_service.dart';
+
+const splitJson = '''
+{
+ "transaction_id": "parent_1",
+ "amount": "\$100.00",
+ "amount_decimal": "100.0",
+ "amount_cents": 10000,
+ "currency": "USD",
+ "children": [
+ {
+ "id": "child_1", "name": "Groceries", "amount": "\$60.00",
+ "currency": "USD", "date": "2026-06-01", "classification": "expense",
+ "account": {"id": "acct_1"},
+ "category": {"id": "cat_food", "name": "Food"},
+ "amount_decimal": "60.0", "excluded": false
+ },
+ {
+ "id": "child_2", "name": "Household", "amount": "\$40.00",
+ "currency": "USD", "date": "2026-06-01", "classification": "expense",
+ "account": {"id": "acct_1"}, "category": null,
+ "amount_decimal": "40.0", "excluded": true
+ }
+ ]
+}
+''';
+
+void main() {
+ group('TransactionSplitsService', () {
+ test('GET parses the split and its children', () async {
+ final service = TransactionSplitsService(
+ client: MockClient((request) async {
+ expect(request.method, 'GET');
+ expect(request.url.path, '/api/v1/transactions/child_1/split');
+ return http.Response(splitJson, 200);
+ }),
+ );
+
+ final result = await service.getSplit(
+ accessToken: 'token',
+ transactionId: 'child_1',
+ );
+
+ expect(result['success'], isTrue);
+ final split = result['split'] as TransactionSplit;
+ expect(split.transactionId, 'parent_1');
+ expect(split.amountUnits, BigInt.from(1000000));
+ expect(split.childIds, ['child_1', 'child_2']);
+ expect(split.children.first.categoryName, 'Food');
+ expect(split.children.last.excluded, isTrue);
+ expect(split.children.last.categoryId, isNull);
+ });
+
+ test('GET treats 404 as "not split" rather than an error', () async {
+ final service = TransactionSplitsService(
+ client: MockClient(
+ (_) async => http.Response(
+ '{"error":"not_found","message":"Transaction is not split"}',
+ 404,
+ ),
+ ),
+ );
+
+ final result = await service.getSplit(
+ accessToken: 'token',
+ transactionId: 'tx_1',
+ );
+
+ expect(result['success'], isTrue);
+ expect(result['split'], isNull);
+ });
+
+ test('GET reports a missing transaction instead of "not split"', () async {
+ final service = TransactionSplitsService(
+ client: MockClient(
+ (_) async => http.Response(
+ '{"error":"record_not_found",'
+ '"message":"The requested resource was not found"}',
+ 404,
+ ),
+ ),
+ );
+
+ final result = await service.getSplit(
+ accessToken: 'token',
+ transactionId: 'gone_1',
+ );
+
+ expect(result['success'], isFalse);
+ expect(result['error'], 'The requested resource was not found');
+ });
+
+ test('GET reports a transaction the lookup cannot find as a failure',
+ () async {
+ // TransactionLookup answers a missing or inaccessible id with the same
+ // "not_found" error code as an unsplit transaction.
+ final service = TransactionSplitsService(
+ client: MockClient(
+ (_) async => http.Response(
+ '{"error":"not_found","message":"Transaction not found"}',
+ 404,
+ ),
+ ),
+ );
+
+ final result = await service.getSplit(
+ accessToken: 'token',
+ transactionId: 'gone_1',
+ );
+
+ expect(result['success'], isFalse);
+ expect(result['error'], 'Transaction not found');
+ });
+
+ test('GET treats a non-JSON 404 as a failure', () async {
+ final service = TransactionSplitsService(
+ client: MockClient((_) async => http.Response('<html></html>', 404)),
+ );
+
+ final result = await service.getSplit(
+ accessToken: 'token',
+ transactionId: 'tx_1',
+ );
+
+ expect(result['success'], isFalse);
+ });
+
+ test('the write timeout also covers a stalled response body', () async {
+ final body = StreamController<List<int>>();
+ addTearDown(body.close);
+ final service = TransactionSplitsService(
+ timeout: const Duration(milliseconds: 50),
+ client: MockClient.streaming((request, _) async {
+ // Headers arrive at once; the body never finishes.
+ return http.StreamedResponse(body.stream, 201);
+ }),
+ );
+
+ final result = await service.createSplit(
+ accessToken: 'token',
+ transactionId: 'tx_1',
+ rows: const [SplitRowInput(name: 'A', amount: '1.0000')],
+ ).timeout(const Duration(seconds: 5));
+
+ expect(result['success'], isFalse);
+ expect(result['error'], startsWith('Network error:'));
+ });
+
+ test('POST and PATCH send the split payload', () async {
+ final seen = <String>[];
+ final service = TransactionSplitsService(
+ client: MockClient((request) async {
+ seen.add(request.method);
+ final body = jsonDecode(request.body) as Map<String, dynamic>;
+ final splits = (body['split'] as Map)['splits'] as List;
+ expect(splits, hasLength(2));
+ expect(splits.first, {
+ 'name': 'Groceries',
+ 'amount': '60.0000',
+ 'category_id': 'cat_food',
+ });
+ expect(splits.last['excluded'], isTrue);
+ return http.Response(
+ splitJson,
+ request.method == 'POST' ? 201 : 200,
+ );
+ }),
+ );
+
+ const rows = [
+ SplitRowInput(
+ name: 'Groceries',
+ amount: '60.0000',
+ categoryId: 'cat_food',
+ ),
+ SplitRowInput(name: 'Household', amount: '40.0000', excluded: true),
+ ];
+
+ final created = await service.createSplit(
+ accessToken: 'token',
+ transactionId: 'parent_1',
+ rows: rows,
+ );
+ final updated = await service.updateSplit(
+ accessToken: 'token',
+ transactionId: 'parent_1',
+ rows: rows,
+ );
+
+ expect(seen, ['POST', 'PATCH']);
+ expect(created['success'], isTrue);
+ expect(updated['split'], isA<TransactionSplit>());
+ });
+
+ test('surfaces validation messages from the API', () async {
+ final service = TransactionSplitsService(
+ client: MockClient(
+ (_) async => http.Response(
+ '{"error":"validation_failed",'
+ '"message":"Transaction cannot be split",'
+ '"errors":["Transaction is part of a transfer"]}',
+ 422,
+ ),
+ ),
+ );
+
+ final result = await service.createSplit(
+ accessToken: 'token',
+ transactionId: 'tx_1',
+ rows: const [SplitRowInput(name: 'A', amount: '1')],
+ );
+
+ expect(result['success'], isFalse);
+ expect(
+ result['error'],
+ 'Transaction cannot be split: Transaction is part of a transfer',
+ );
+ });
+
+ test('DELETE succeeds on 204', () async {
+ final service = TransactionSplitsService(
+ client: MockClient((request) async {
+ expect(request.method, 'DELETE');
+ return http.Response('', 204);
+ }),
+ );
+
+ final result = await service.deleteSplit(
+ accessToken: 'token',
+ transactionId: 'parent_1',
+ );
+
+ expect(result['success'], isTrue);
+ });
+ });
+}
diff --git a/mobile/test/utils/split_list_grouping_test.dart b/mobile/test/utils/split_list_grouping_test.dart
new file mode 100644
index 0000000000..4dbeb94316
--- /dev/null
+++ b/mobile/test/utils/split_list_grouping_test.dart
@@ -0,0 +1,55 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:sure_mobile/utils/split_list_grouping.dart';
+
+void main() {
+ List<SplitListEntry<String>> group(
+ List<String> ids, {
+ Map<String, List<String>> splits = const {},
+ }) {
+ final parentOf = <String, String>{
+ for (final entry in splits.entries)
+ for (final child in entry.value) child: entry.key,
+ };
+ return groupSplitEntries<String>(
+ ids,
+ idOf: (id) => id,
+ childIdsOf: (id) => splits[id],
+ parentIdOf: (id) => parentOf[id],
+ );
+ }
+
+ test('passes unknown transactions through in order', () {
+ final entries = group(['a', 'b', 'c']);
+ expect(entries.map((e) => e.item), ['a', 'b', 'c']);
+ expect(entries.every((e) => e.role == SplitRole.none), isTrue);
+ });
+
+ test('places children directly under their parent in split order', () {
+ // The API returns parent and children as separate rows in any order.
+ final entries = group(
+ ['c2', 'x', 'p', 'c1'],
+ splits: {
+ 'p': ['c1', 'c2'],
+ },
+ );
+
+ expect(entries.map((e) => e.item), ['x', 'p', 'c1', 'c2']);
+ expect(entries[1].role, SplitRole.parent);
+ expect(entries[2].role, SplitRole.child);
+ expect(entries[2].grouped, isTrue);
+ expect(entries[3].grouped, isTrue);
+ });
+
+ test('keeps a child whose parent is not listed, marked as a child', () {
+ final entries = group(
+ ['c1', 'y'],
+ splits: {
+ 'p': ['c1', 'c2'],
+ },
+ );
+
+ expect(entries.map((e) => e.item), ['c1', 'y']);
+ expect(entries.first.role, SplitRole.child);
+ expect(entries.first.grouped, isFalse);
+ });
+}
diff --git a/mobile/test/utils/split_math_test.dart b/mobile/test/utils/split_math_test.dart
new file mode 100644
index 0000000000..4c456e1589
--- /dev/null
+++ b/mobile/test/utils/split_math_test.dart
@@ -0,0 +1,173 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:sure_mobile/utils/split_math.dart';
+
+BigInt u(String value) => SplitMath.parseUnits(value)!;
+
+void main() {
+ group('SplitMath.parseUnits', () {
+ test('parses plain decimals into 1/10000 units', () {
+ expect(u('12.5'), BigInt.from(125000));
+ expect(u('-0.0001'), BigInt.from(-1));
+ expect(u('100'), BigInt.from(1000000));
+ expect(u('.5'), BigInt.from(5000));
+ });
+
+ test('accepts the API decimal(19,4) strings and exponents', () {
+ expect(u('33.3333'), BigInt.from(333333));
+ expect(u('100.0'), BigInt.from(1000000));
+ expect(u('0.1e3'), BigInt.from(1000000));
+ expect(u('1.50000'), BigInt.from(15000));
+ });
+
+ test('rejects garbage and more than four significant decimals', () {
+ expect(SplitMath.parseUnits(''), isNull);
+ expect(SplitMath.parseUnits('abc'), isNull);
+ expect(SplitMath.parseUnits('1.2.3'), isNull);
+ expect(SplitMath.parseUnits('0.00001'), isNull);
+ });
+ });
+
+ group('SplitMath.parseUserInput', () {
+ test('rejects signs that are not a single leading sign', () {
+ expect(SplitMath.parseUserInput('12\u22123', locale: 'en'), isNull);
+ expect(SplitMath.parseUserInput('1\u2212', locale: 'en'), isNull);
+ expect(SplitMath.parseUserInput('--5', locale: 'en'), isNull);
+ expect(SplitMath.parseUserInput('\u22125', locale: 'en'),
+ BigInt.from(-50000));
+ });
+ test('handles grouping and the locale decimal separator', () {
+ expect(
+ SplitMath.parseUserInput('1,234.56', locale: 'en'),
+ BigInt.from(12345600),
+ );
+ expect(
+ SplitMath.parseUserInput('1.234,56', locale: 'sv'),
+ BigInt.from(12345600),
+ );
+ expect(
+ SplitMath.parseUserInput('1\u00A0234,56', locale: 'sv'),
+ BigInt.from(12345600),
+ );
+ expect(SplitMath.parseUserInput('-12', locale: 'en'), u('-12'));
+ expect(SplitMath.parseUserInput('12abc', locale: 'en'), isNull);
+ });
+ });
+
+ group('currency precision', () {
+ test('knows zero- and three-decimal currencies', () {
+ expect(SplitMath.currencyDecimals('USD'), 2);
+ expect(SplitMath.currencyDecimals('JPY'), 0);
+ expect(SplitMath.currencyDecimals('KWD'), 3);
+ expect(SplitMath.currencyDecimals(''), 2);
+ });
+
+ test('widens input precision only for a finer stored parent amount', () {
+ expect(SplitMath.inputDecimals('USD', u('100.00')), 2);
+ expect(SplitMath.inputDecimals('USD', u('100.125')), 3);
+ expect(SplitMath.inputDecimals('JPY', u('1500')), 0);
+ });
+
+ test('widens input precision for a finer existing child', () {
+ expect(
+ SplitMath.inputDecimals('USD', u('100.00'),
+ childUnits: [u('33.3333'), u('66.6667')]),
+ 4,
+ );
+ });
+
+ test('validateAmount reports the first problem', () {
+ expect(
+ SplitMath.validateAmount('', decimals: 2, locale: 'en'),
+ SplitAmountError.required,
+ );
+ expect(
+ SplitMath.validateAmount('abc', decimals: 2, locale: 'en'),
+ SplitAmountError.invalid,
+ );
+ expect(
+ SplitMath.validateAmount('0.00', decimals: 2, locale: 'en'),
+ SplitAmountError.zero,
+ );
+ expect(
+ SplitMath.validateAmount('10.005', decimals: 2, locale: 'en'),
+ SplitAmountError.tooPrecise,
+ );
+ expect(
+ SplitMath.validateAmount('10.5', decimals: 0, locale: 'en'),
+ SplitAmountError.tooPrecise,
+ );
+ expect(
+ SplitMath.validateAmount('10.50', decimals: 2, locale: 'en'),
+ isNull,
+ );
+ });
+ });
+
+ group('remaining', () {
+ test('is exact where doubles are not', () {
+ // 0.1 + 0.2 != 0.3 in floating point; it must balance here.
+ final remaining = SplitMath.remaining(
+ u('0.3'),
+ ['0.1', '0.2'],
+ locale: 'en',
+ );
+ expect(remaining, BigInt.zero);
+ });
+
+ test('ignores unparseable rows and goes negative when over-allocated', () {
+ expect(
+ SplitMath.remaining(u('100'), ['60', '', 'x'], locale: 'en'),
+ u('40'),
+ );
+ expect(
+ SplitMath.remaining(u('100'), ['60', '50'], locale: 'en'),
+ u('-10'),
+ );
+ });
+ });
+
+ group('formatting', () {
+ test('toDecimalString keeps exact values', () {
+ expect(SplitMath.toDecimalString(u('60')), '60.0000');
+ expect(SplitMath.toDecimalString(u('60'), decimals: 2), '60.00');
+ expect(SplitMath.toDecimalString(u('-0.5'), decimals: 0), '-0.5');
+ expect(SplitMath.toDecimalString(u('1500'), decimals: 0), '1500');
+ });
+
+ test('formatMoney uses the currency precision', () {
+ expect(
+ SplitMath.formatMoney(u('1234.5'), 'USD', decimals: 2, locale: 'en'),
+ r'$1,234.50',
+ );
+ expect(
+ SplitMath.formatMoney(u('1500'), 'JPY', decimals: 0, locale: 'en'),
+ contains('1,500'),
+ );
+ });
+
+ test('formatMoney keeps every digit of large decimal(19,4) values', () {
+ // 123456789012345.6789 has 19 significant digits; a double keeps ~16.
+ expect(
+ SplitMath.formatMoney(
+ u('123456789012345.6789'),
+ 'USD',
+ decimals: 2,
+ locale: 'en',
+ ),
+ r'$123,456,789,012,345.6789',
+ );
+ expect(
+ SplitMath.formatMoney(u('-0.5'), 'USD', decimals: 2, locale: 'en'),
+ r'-$0.50',
+ );
+ expect(
+ SplitMath.formatMoney(u('-1234.5'), 'EUR', decimals: 2, locale: 'de'),
+ startsWith('-1.234,50'),
+ );
+ final sv =
+ SplitMath.formatMoney(u('1234.5'), 'SEK', decimals: 2, locale: 'sv');
+ expect(sv, contains('234,50'));
+ expect(sv, contains('kr'));
+ });
+ });
+}
diff --git a/mobile/test/widgets/transaction_split_test.dart b/mobile/test/widgets/transaction_split_test.dart
new file mode 100644
index 0000000000..523f8dd073
--- /dev/null
+++ b/mobile/test/widgets/transaction_split_test.dart
@@ -0,0 +1,886 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:http/http.dart' as http;
+import 'package:http/testing.dart';
+import 'package:provider/provider.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+import 'package:sure_mobile/l10n/app_localizations.dart';
+import 'package:sure_mobile/models/category.dart' as models;
+import 'package:sure_mobile/models/offline_transaction.dart';
+import 'package:sure_mobile/models/transaction_split.dart';
+import 'package:sure_mobile/providers/auth_provider.dart';
+import 'package:sure_mobile/providers/categories_provider.dart';
+import 'package:sure_mobile/providers/privacy_provider.dart';
+import 'package:sure_mobile/providers/transaction_splits_provider.dart';
+import 'package:sure_mobile/providers/transactions_provider.dart';
+import 'package:sure_mobile/screens/transaction_split_screen.dart';
+import 'package:sure_mobile/services/connectivity_service.dart';
+import 'package:sure_mobile/services/preferences_service.dart';
+import 'package:sure_mobile/services/transaction_splits_service.dart';
+import 'package:sure_mobile/theme/sure_theme.dart';
+import 'package:sure_mobile/utils/split_math.dart';
+import 'package:sure_mobile/widgets/sure_button.dart';
+import 'package:sure_mobile/widgets/transaction_split_section.dart';
+
+class _FakeAuthProvider extends ChangeNotifier implements AuthProvider {
+ _FakeAuthProvider({this.token = 'token'});
+
+ final String? token;
+
+ @override
+ Future<String?> getValidAccessToken() async => token;
+
+ @override
+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
+}
+
+class _FakeConnectivity extends ChangeNotifier implements ConnectivityService {
+ _FakeConnectivity({required this.online});
+
+ bool online;
+
+ void setOnline(bool value) {
+ online = value;
+ notifyListeners();
+ }
+
+ @override
+ bool get isOnline => online;
+
+ @override
+ bool get isOffline => !online;
+
+ @override
+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
+}
+
+class _FakeCategoriesProvider extends CategoriesProvider {
+ @override
+ List<models.Category> get categories => [
+ models.Category(id: 'cat_food', name: 'Food'),
+ models.Category(id: 'cat_home', name: 'Home'),
+ ];
+
+ @override
+ Future<void> fetchCategories({required String accessToken}) async {}
+}
+
+class _RecordingTransactionsProvider extends TransactionsProvider {
+ final List<List<String>> refreshes = [];
+
+ @override
+ Future<void> refreshAfterSplitChange({
+ required String accessToken,
+ required String accountId,
+ List<String> removedChildIds = const [],
+ }) async {
+ refreshes.add(removedChildIds);
+ }
+}
+
+String _splitJson({
+ String parentId = 'parent_1',
+ String amountDecimal = '100.0',
+}) {
+ return jsonEncode({
+ 'transaction_id': parentId,
+ 'amount': r'$100.00',
+ 'amount_decimal': amountDecimal,
+ 'amount_cents': 10000,
+ 'currency': 'USD',
+ 'children': [
+ {
+ 'id': 'child_1',
+ 'name': 'Groceries',
+ 'amount': r'$60.00',
+ 'currency': 'USD',
+ 'date': '2026-06-01',
+ 'classification': 'expense',
+ 'account': {'id': 'acct_1'},
+ 'category': {'id': 'cat_food', 'name': 'Food'},
+ 'amount_decimal': '60.0',
+ 'excluded': false,
+ },
+ {
+ 'id': 'child_2',
+ 'name': 'Household',
+ 'amount': r'$40.00',
+ 'currency': 'USD',
+ 'date': '2026-06-01',
+ 'classification': 'expense',
+ 'account': {'id': 'acct_1'},
+ 'category': null,
+ 'amount_decimal': '40.0',
+ 'excluded': true,
+ },
+ ],
+ });
+}
+
+class _Harness {
+ _Harness({
+ bool online = true,
+ bool hidden = false,
+ MockClientHandler? handler,
+ String? token = 'token',
+ }) : auth = _FakeAuthProvider(token: token),
+ privacy = PrivacyProvider(initialHidden: hidden),
+ connectivity = _FakeConnectivity(online: online),
+ transactions = _RecordingTransactionsProvider() {
+ splits = TransactionSplitsProvider(
+ service: TransactionSplitsService(
+ client: MockClient((request) async {
+ requests.add(request);
+ if (handler != null) return handler(request);
+ return http.Response(_splitJson(), 200);
+ }),
+ ),
+ )..setConnectivityService(connectivity);
+ }
+
+ final _FakeAuthProvider auth;
+ final _FakeConnectivity connectivity;
+ final PrivacyProvider privacy;
+ final _RecordingTransactionsProvider transactions;
+ late final TransactionSplitsProvider splits;
+ final List<http.Request> requests = [];
+
+ Widget wrap(Widget child) {
+ return MultiProvider(
+ providers: [
+ ChangeNotifierProvider<AuthProvider>.value(value: auth),
+ ChangeNotifierProvider<CategoriesProvider>.value(
+ value: _FakeCategoriesProvider(),
+ ),
+ ChangeNotifierProvider<PrivacyProvider>.value(value: privacy),
+ ChangeNotifierProvider<TransactionsProvider>.value(
+ value: transactions,
+ ),
+ ChangeNotifierProvider<TransactionSplitsProvider>.value(value: splits),
+ ],
+ child: MaterialApp(
+ theme: SureTheme.light,
+ locale: const Locale('en'),
+ localizationsDelegates: AppLocalizations.localizationsDelegates,
+ supportedLocales: AppLocalizations.supportedLocales,
+ home: child,
+ ),
+ );
+ }
+}
+
+/// Pushes [child] on top of a blank home so the editor can pop on save.
+class _Launcher extends StatefulWidget {
+ const _Launcher(this.child);
+
+ final Widget child;
+
+ @override
+ State<_Launcher> createState() => _LauncherState();
+}
+
+class _LauncherState extends State<_Launcher> {
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ Navigator.of(context).push(
+ MaterialPageRoute<bool>(builder: (_) => widget.child),
+ );
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) => const Scaffold();
+}
+
+SplitEditorTarget _target({String amount = '100', String currency = 'USD'}) {
+ return SplitEditorTarget(
+ transactionId: 'parent_1',
+ accountId: 'acct_1',
+ name: 'Costco',
+ date: '2026-06-01',
+ currency: currency,
+ categoryId: 'cat_food',
+ amountUnits: SplitMath.parseUnits(amount)!,
+ );
+}
+
+Finder _field(String key) => find.descendant(
+ of: find.byKey(Key(key)),
+ matching: find.byType(TextFormField),
+ );
+
+String _remaining(WidgetTester tester) =>
+ tester.widget<Text>(find.byKey(const Key('split-remaining-amount'))).data!;
+
+bool _saveEnabled(WidgetTester tester) =>
+ tester.widget<SureButton>(find.byKey(const Key('split-save'))).onPressed !=
+ null;
+
+void main() {
+ setUp(() {
+ SharedPreferences.setMockInitialValues({});
+ PreferencesService.resetForTest();
+ });
+
+ Future<void> useTallView(WidgetTester tester) async {
+ tester.view.physicalSize = const Size(1080, 3200);
+ tester.view.devicePixelRatio = 1.0;
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ }
+
+ group('TransactionSplitScreen', () {
+ testWidgets('tracks the remaining amount and only saves when balanced',
+ (tester) async {
+ await useTallView(tester);
+ final harness = _Harness(
+ handler: (_) async => http.Response(_splitJson(), 201),
+ );
+ await tester.pumpWidget(
+ harness.wrap(_Launcher(TransactionSplitScreen(target: _target()))),
+ );
+ await tester.pumpAndSettle();
+
+ expect(find.text('Costco'), findsWidgets);
+ expect(_remaining(tester), r'$100.00');
+ expect(_saveEnabled(tester), isFalse);
+
+ await tester.enterText(_field('split-amount-0'), '60');
+ await tester.pump();
+ expect(_remaining(tester), r'$40.00');
+ expect(_saveEnabled(tester), isFalse);
+
+ await tester.enterText(_field('split-name-1'), 'Household');
+ await tester.enterText(_field('split-amount-1'), '40.5');
+ await tester.pump();
+ expect(_remaining(tester), r'-$0.50');
+ expect(
+ find.text('Split amounts must equal the original transaction amount.'),
+ findsOneWidget,
+ );
+
+ await tester.enterText(_field('split-amount-1'), '40');
+ await tester.pump();
+ expect(_remaining(tester), r'$0.00');
+ expect(_saveEnabled(tester), isTrue);
+
+ await tester.tap(find.byKey(const Key('split-save')));
+ await tester.pumpAndSettle();
+
+ expect(harness.requests, hasLength(1));
+ final request = harness.requests.single;
+ expect(request.method, 'POST');
+ final splits =
+ ((jsonDecode(request.body) as Map)['split'] as Map)['splits'] as List;
+ expect(splits[0], {
+ 'name': 'Costco',
+ 'amount': '60.0000',
+ 'category_id': 'cat_food',
+ });
+ expect(splits[1], {
+ 'name': 'Household',
+ 'amount': '40.0000',
+ 'category_id': null,
+ });
+ expect(harness.transactions.refreshes, hasLength(1));
+ expect(harness.splits.isSplitParent('parent_1'), isTrue);
+ });
+
+ testWidgets('sends income amounts with the parent sign', (tester) async {
+ await useTallView(tester);
+ final harness = _Harness(
+ handler: (_) async =>
+ http.Response(_splitJson(amountDecimal: '-100.0'), 201),
+ );
+ await tester.pumpWidget(
+ harness.wrap(
+ _Launcher(TransactionSplitScreen(target: _target(amount: '-100'))),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ expect(_remaining(tester), r'$100.00');
+ await tester.enterText(_field('split-amount-0'), '70');
+ await tester.enterText(_field('split-name-1'), 'Bonus');
+ await tester.enterText(_field('split-amount-1'), '30');
+ await tester.pump();
+ await tester.tap(find.byKey(const Key('split-save')));
+ await tester.pumpAndSettle();
+
+ final splits = ((jsonDecode(harness.requests.single.body) as Map)['split']
+ as Map)['splits'] as List;
+ expect(splits.map((s) => s['amount']), ['-70.0000', '-30.0000']);
+ });
+
+ testWidgets('rejects amounts finer than the currency allows',
+ (tester) async {
+ await useTallView(tester);
+ final harness = _Harness();
+ await tester.pumpWidget(
+ harness.wrap(
+ _Launcher(
+ TransactionSplitScreen(
+ target: _target(amount: '1500', currency: 'JPY'),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ await tester.enterText(_field('split-amount-0'), '1000.5');
+ await tester.pump();
+ expect(find.text('Use at most 0 decimal places'), findsOneWidget);
+ expect(_saveEnabled(tester), isFalse);
+ });
+
+ testWidgets('editing prefills rows and replaces the split with PATCH',
+ (tester) async {
+ await useTallView(tester);
+ final harness = _Harness();
+ final existing = TransactionSplit.fromJson(
+ jsonDecode(_splitJson()) as Map<String, dynamic>,
+ );
+ harness.splits.remember(existing);
+
+ await tester.pumpWidget(
+ harness.wrap(
+ _Launcher(
+ TransactionSplitScreen(target: _target(), existing: existing),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ expect(find.text('Edit split'), findsOneWidget);
+ expect(find.text('60.00'), findsOneWidget);
+ expect(find.text('40.00'), findsOneWidget);
+ expect(_remaining(tester), r'$0.00');
+
+ // Removing a row unbalances the split until the amount is reassigned.
+ await tester.tap(find.byKey(const Key('split-remove-row-1')));
+ await tester.pump();
+ expect(_remaining(tester), r'$40.00');
+ expect(_saveEnabled(tester), isFalse);
+
+ await tester.tap(find.byKey(const Key('split-add-row')));
+ await tester.pump();
+ await tester.enterText(_field('split-name-1'), 'Household');
+ await tester.enterText(_field('split-amount-1'), '40');
+ await tester.pump();
+ await tester.tap(find.byKey(const Key('split-save')));
+ await tester.pumpAndSettle();
+
+ expect(harness.requests.single.method, 'PATCH');
+ // Response reuses the same child ids, so nothing is reported removed.
+ expect(harness.transactions.refreshes.single, isEmpty);
+ });
+
+ testWidgets('a balanced split with an empty name explains why on Save',
+ (tester) async {
+ await useTallView(tester);
+ final harness = _Harness();
+ await tester.pumpWidget(
+ harness.wrap(_Launcher(TransactionSplitScreen(target: _target()))),
+ );
+ await tester.pumpAndSettle();
+
+ await tester.enterText(_field('split-amount-0'), '60');
+ await tester.enterText(_field('split-amount-1'), '40');
+ await tester.pump();
+ expect(_remaining(tester), r'$0.00');
+ expect(_saveEnabled(tester), isTrue);
+
+ await tester.tap(find.byKey(const Key('split-save')));
+ await tester.pumpAndSettle();
+
+ expect(find.text('Name is required'), findsOneWidget);
+ expect(harness.requests, isEmpty);
+ });
+
+ testWidgets('edits a split stored with four decimals exactly',
+ (tester) async {
+ await useTallView(tester);
+ final json = jsonDecode(_splitJson(amountDecimal: '100.0012'))
+ as Map<String, dynamic>;
+ final children = json['children'] as List;
+ (children[0] as Map)['amount_decimal'] = '60.0001';
+ (children[1] as Map)['amount_decimal'] = '40.0011';
+ final existing = TransactionSplit.fromJson(json);
+ final harness = _Harness(
+ handler: (_) async => http.Response(jsonEncode(json), 200),
+ );
+ harness.splits.remember(existing);
+
+ await tester.pumpWidget(
+ harness.wrap(
+ _Launcher(
+ TransactionSplitScreen(
+ target: _target(amount: '100.0012'),
+ existing: existing,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ expect(find.text('60.0001'), findsOneWidget);
+ expect(find.text('40.0011'), findsOneWidget);
+ expect(_remaining(tester), r'$0.0000');
+ expect(_saveEnabled(tester), isTrue);
+
+ // Replace the second row with a newly added one.
+ await tester.tap(find.byKey(const Key('split-remove-row-1')));
+ await tester.pump();
+ expect(_remaining(tester), r'$40.0011');
+ await tester.tap(find.byKey(const Key('split-add-row')));
+ await tester.pump();
+ await tester.enterText(_field('split-name-1'), 'Household');
+ await tester.enterText(_field('split-amount-1'), '40.0011');
+ await tester.pump();
+ expect(_remaining(tester), r'$0.0000');
+
+ await tester.tap(find.byKey(const Key('split-save')));
+ await tester.pumpAndSettle();
+
+ final request = harness.requests.single;
+ expect(request.method, 'PATCH');
+ final splits =
+ ((jsonDecode(request.body) as Map)['split'] as Map)['splits'] as List;
+ expect(splits.map((s) => s['amount']), ['60.0001', '40.0011']);
+ });
+
+ testWidgets('masks amounts in privacy mode', (tester) async {
+ await useTallView(tester);
+ final harness = _Harness(hidden: true);
+ await tester.pumpWidget(
+ harness.wrap(_Launcher(TransactionSplitScreen(target: _target()))),
+ );
+ await tester.pumpAndSettle();
+
+ expect(
+ tester
+ .widget<Text>(find.byKey(const Key('split-original-amount')))
+ .data,
+ r'$••••',
+ );
+ expect(_remaining(tester), r'$••••');
+ final amountField = tester.widget<EditableText>(
+ find.descendant(
+ of: find.byKey(const Key('split-amount-0')),
+ matching: find.byType(EditableText),
+ ),
+ );
+ expect(amountField.obscureText, isTrue);
+ });
+
+ testWidgets('cannot save while offline', (tester) async {
+ await useTallView(tester);
+ final harness = _Harness(online: false);
+ await tester.pumpWidget(
+ harness.wrap(_Launcher(TransactionSplitScreen(target: _target()))),
+ );
+ await tester.pumpAndSettle();
+
+ await tester.enterText(_field('split-amount-0'), '60');
+ await tester.enterText(_field('split-name-1'), 'Household');
+ await tester.enterText(_field('split-amount-1'), '40');
+ await tester.pump();
+
+ expect(
+ find.text("You're offline. Splits can only be saved while connected."),
+ findsOneWidget,
+ );
+ expect(_saveEnabled(tester), isFalse);
+ expect(harness.requests, isEmpty);
+ });
+ });
+
+ group('TransactionSplitSection', () {
+ OfflineTransaction transaction(String id) => OfflineTransaction(
+ id: id,
+ localId: 'local_$id',
+ accountId: 'acct_1',
+ name: 'Costco',
+ date: '2026-06-01',
+ amount: r'$100.00',
+ currency: 'USD',
+ nature: 'expense',
+ syncStatus: SyncStatus.synced,
+ );
+
+ Widget screen(OfflineTransaction t) => Scaffold(
+ body: SingleChildScrollView(
+ child: TransactionSplitSection(transaction: t),
+ ),
+ );
+
+ testWidgets('lists the children of a split parent', (tester) async {
+ await useTallView(tester);
+ final harness = _Harness();
+ await tester.pumpWidget(harness.wrap(screen(transaction('parent_1'))));
+ await tester.pumpAndSettle();
+
+ expect(find.text('Split entries'), findsOneWidget);
+ expect(find.text('Groceries'), findsOneWidget);
+ expect(find.text('Food'), findsOneWidget);
+ expect(find.text('(uncategorized)'), findsOneWidget);
+ expect(find.text(r'$60.00'), findsOneWidget);
+ expect(find.text(r'$40.00'), findsOneWidget);
+ expect(find.text('Edit split'), findsOneWidget);
+ expect(find.text('Unsplit'), findsOneWidget);
+ });
+
+ testWidgets('marks a child as part of a split', (tester) async {
+ await useTallView(tester);
+ final harness = _Harness();
+ await tester.pumpWidget(harness.wrap(screen(transaction('child_1'))));
+ await tester.pumpAndSettle();
+
+ expect(find.text('Part of split'), findsOneWidget);
+ expect(harness.splits.isSplitChild('child_1'), isTrue);
+ expect(harness.splits.parentIdFor('child_1'), 'parent_1');
+ });
+
+ testWidgets('offers to split an unsplit transaction', (tester) async {
+ await useTallView(tester);
+ final harness = _Harness(
+ handler: (_) async => http.Response(
+ '{"error":"not_found","message":"Transaction is not split"}',
+ 404,
+ ),
+ );
+ await tester.pumpWidget(harness.wrap(screen(transaction('tx_1'))));
+ await tester.pumpAndSettle();
+
+ expect(find.byKey(const Key('split-start')), findsOneWidget);
+
+ await tester.tap(find.byKey(const Key('split-start')));
+ await tester.pumpAndSettle();
+ expect(find.byType(TransactionSplitScreen), findsOneWidget);
+ expect(_remaining(tester), r'$100.00');
+ });
+
+ testWidgets('unsplit asks first, then calls DELETE', (tester) async {
+ await useTallView(tester);
+ final harness = _Harness(
+ handler: (request) async => request.method == 'DELETE'
+ ? http.Response('', 204)
+ : http.Response(_splitJson(), 200),
+ );
+ await tester.pumpWidget(harness.wrap(screen(transaction('parent_1'))));
+ await tester.pumpAndSettle();
+
+ await tester.tap(find.byKey(const Key('split-unsplit')));
+ await tester.pumpAndSettle();
+ expect(find.text('Unsplit transaction'), findsOneWidget);
+
+ await tester.tap(find.widgetWithText(TextButton, 'Unsplit'));
+ await tester.pumpAndSettle();
+
+ expect(harness.requests.last.method, 'DELETE');
+ expect(harness.splits.isSplitParent('parent_1'), isFalse);
+ expect(
+ harness.transactions.refreshes.single,
+ ['child_1', 'child_2'],
+ );
+ });
+
+ testWidgets('masks child amounts in privacy mode', (tester) async {
+ await useTallView(tester);
+ final harness = _Harness(hidden: true);
+ await tester.pumpWidget(harness.wrap(screen(transaction('parent_1'))));
+ await tester.pumpAndSettle();
+
+ expect(find.text(r'$60.00'), findsNothing);
+ expect(find.text(r'$••••'), findsNWidgets(2));
+ });
+
+ testWidgets('is read-only offline', (tester) async {
+ await useTallView(tester);
+ final harness = _Harness(online: false);
+ harness.splits.remember(
+ TransactionSplit.fromJson(
+ jsonDecode(_splitJson()) as Map<String, dynamic>,
+ ),
+ );
+ await tester.pumpWidget(harness.wrap(screen(transaction('parent_1'))));
+ await tester.pumpAndSettle();
+
+ expect(
+ find.text('Connect to the internet to load or edit split details.'),
+ findsOneWidget,
+ );
+ expect(
+ tester
+ .widget<SureButton>(find.byKey(const Key('split-edit')))
+ .onPressed,
+ isNull,
+ );
+ expect(harness.requests, isEmpty);
+ });
+
+ testWidgets('offers a retry when the split lookup fails', (tester) async {
+ await useTallView(tester);
+ var fail = true;
+ final harness = _Harness(
+ handler: (_) async => fail
+ ? http.Response('{"error":"boom"}', 500)
+ : http.Response(_splitJson(), 200),
+ );
+ await tester.pumpWidget(harness.wrap(screen(transaction('parent_1'))));
+ await tester.pumpAndSettle();
+
+ expect(find.text("Couldn't load split details."), findsOneWidget);
+ expect(harness.splits.isSplitStatusKnown('parent_1'), isFalse);
+
+ fail = false;
+ await tester.tap(find.byKey(const Key('split-retry')));
+ await tester.pumpAndSettle();
+
+ expect(find.text('Split entries'), findsOneWidget);
+ expect(harness.splits.isSplitStatusKnown('parent_1'), isTrue);
+ });
+
+ testWidgets('offers a retry instead of spinning when the session expired',
+ (tester) async {
+ await useTallView(tester);
+ final harness = _Harness(token: null);
+ await tester.pumpWidget(harness.wrap(screen(transaction('parent_1'))));
+ await tester.pumpAndSettle();
+
+ expect(find.byType(CircularProgressIndicator), findsNothing);
+ expect(find.text("Couldn't load split details."), findsOneWidget);
+ expect(find.byKey(const Key('split-retry')), findsOneWidget);
+ expect(harness.splits.isSplitStatusKnown('parent_1'), isFalse);
+ expect(harness.requests, isEmpty);
+ });
+
+ testWidgets('retries the lookup after reconnecting', (tester) async {
+ await useTallView(tester);
+ final harness = _Harness(online: false);
+ await tester.pumpWidget(harness.wrap(screen(transaction('parent_1'))));
+ await tester.pumpAndSettle();
+ expect(harness.requests, isEmpty);
+
+ harness.connectivity.setOnline(true);
+ await tester.pumpAndSettle();
+
+ expect(harness.requests, hasLength(1));
+ expect(find.text('Split entries'), findsOneWidget);
+ });
+ });
+
+ group('TransactionSplitsProvider', () {
+ test('notifies listeners when connectivity changes', () {
+ final harness = _Harness(online: false);
+ var notified = 0;
+ harness.splits.addListener(() => notified++);
+
+ harness.connectivity.setOnline(true);
+ expect(notified, 1);
+ expect(harness.splits.isOnline, isTrue);
+
+ harness.splits.dispose();
+ harness.connectivity.setOnline(false);
+ expect(notified, 1);
+ });
+
+ test('a failed lookup does not lock editing; success records membership',
+ () async {
+ final harness = _Harness(
+ handler: (_) async => http.Response('{"error":"boom"}', 500),
+ );
+ expect(harness.splits.isSplitStatusKnown('child_1'), isFalse);
+ await harness.splits
+ .loadSplit(accessToken: 'token', transactionId: 'child_1');
+ expect(harness.splits.isSplitStatusKnown('child_1'), isFalse);
+ expect(harness.splits.canEditAfterLookup('child_1'), isTrue);
+ expect(harness.splits.isSplitChild('child_1'), isFalse);
+
+ final ok = _Harness();
+ await ok.splits.loadSplit(accessToken: 'token', transactionId: 'child_1');
+ expect(ok.splits.isSplitStatusKnown('child_1'), isTrue);
+ expect(ok.splits.isSplitStatusKnown('child_2'), isTrue);
+ expect(ok.splits.isSplitChild('child_1'), isTrue);
+ });
+
+ test('hides session and network errors, keeps validation messages',
+ () async {
+ const rows = [SplitRowInput(name: 'A', amount: '100')];
+ Future<String?> errorFor(http.Response response) async {
+ final harness = _Harness(handler: (_) async => response);
+ final result = await harness.splits.saveSplit(
+ accessToken: 'token',
+ transactionId: 'parent_1',
+ rows: rows,
+ replace: false,
+ );
+ expect(result.success, isFalse);
+ return result.error;
+ }
+
+ expect(await errorFor(http.Response('{}', 401)), isNull);
+ expect(
+ await errorFor(http.Response(
+ '{"error":"validation_failed","message":"Splits must sum to the '
+ 'transaction amount"}',
+ 422,
+ )),
+ contains('sum'),
+ );
+
+ final offline = _Harness(
+ handler: (_) async => throw http.ClientException('reset'),
+ );
+ final unsplit = await offline.splits
+ .unsplit(accessToken: 'token', transactionId: 'parent_1');
+ expect(unsplit.success, isFalse);
+ expect(unsplit.error, isNull);
+ });
+
+ group('checkBeforeDelete', () {
+ const notSplit =
+ '{"error":"not_found","message":"Transaction is not split"}';
+
+ test('blocks split parents and children, allows unsplit rows', () async {
+ final harness = _Harness();
+ expect(
+ await harness.splits.checkBeforeDelete(
+ accessToken: 'token', transactionId: 'child_1'),
+ SplitDeleteStatus.split,
+ );
+ expect(
+ await harness.splits.checkBeforeDelete(
+ accessToken: 'token', transactionId: 'parent_1'),
+ SplitDeleteStatus.split,
+ );
+
+ final plain = _Harness(
+ handler: (_) async => http.Response(notSplit, 404),
+ );
+ expect(
+ await plain.splits
+ .checkBeforeDelete(accessToken: 'token', transactionId: 'tx_1'),
+ SplitDeleteStatus.allowed,
+ );
+ });
+
+ test('a failed lookup while online is unknown, not unsplit', () async {
+ final harness = _Harness(
+ handler: (_) async => http.Response('{"error":"boom"}', 500),
+ );
+ expect(
+ await harness.splits.checkBeforeDelete(
+ accessToken: 'token', transactionId: 'parent_1'),
+ SplitDeleteStatus.unknown,
+ );
+ expect(
+ await harness.splits
+ .checkBeforeDelete(accessToken: null, transactionId: 'parent_1'),
+ SplitDeleteStatus.unknown,
+ );
+ });
+
+ test('fresh re-checks a row that was split elsewhere', () async {
+ var split = false;
+ final harness = _Harness(
+ handler: (_) async => split
+ ? http.Response(_splitJson(), 200)
+ : http.Response(notSplit, 404),
+ );
+ expect(
+ await harness.splits.checkBeforeDelete(
+ accessToken: 'token', transactionId: 'parent_1'),
+ SplitDeleteStatus.allowed,
+ );
+
+ split = true; // split on the web after the first lookup
+ expect(
+ await harness.splits.checkBeforeDelete(
+ accessToken: 'token', transactionId: 'parent_1'),
+ SplitDeleteStatus.allowed,
+ reason: 'cached status is reused when not fresh',
+ );
+ expect(
+ await harness.splits.checkBeforeDelete(
+ accessToken: 'token',
+ transactionId: 'parent_1',
+ fresh: true,
+ ),
+ SplitDeleteStatus.split,
+ );
+ expect(harness.requests, hasLength(2));
+ });
+
+ test('offline, only splits known on the device are blocked', () async {
+ final harness = _Harness(online: false);
+ expect(
+ await harness.splits
+ .checkBeforeDelete(accessToken: null, transactionId: 'tx_1'),
+ SplitDeleteStatus.allowed,
+ );
+ harness.splits.remember(
+ TransactionSplit.fromJson(
+ jsonDecode(_splitJson()) as Map<String, dynamic>,
+ ),
+ );
+ expect(
+ await harness.splits.checkBeforeDelete(
+ accessToken: null,
+ transactionId: 'child_2',
+ fresh: true,
+ ),
+ SplitDeleteStatus.split,
+ );
+ expect(harness.requests, isEmpty);
+ });
+ });
+
+ test('stays loading until every overlapping lookup has finished', () async {
+ final responses = <Completer<http.Response>>[];
+ final harness = _Harness(
+ handler: (_) {
+ final response = Completer<http.Response>();
+ responses.add(response);
+ return response.future;
+ },
+ );
+
+ final first = harness.splits
+ .loadSplit(accessToken: 'token', transactionId: 'parent_1');
+ final second = harness.splits
+ .loadSplit(accessToken: 'token', transactionId: 'parent_1');
+ await Future<void>.delayed(Duration.zero);
+ expect(responses, hasLength(2));
+
+ responses[0].complete(http.Response(_splitJson(), 200));
+ await first;
+ expect(harness.splits.isLoading('parent_1'), isTrue);
+
+ responses[1].complete(http.Response(_splitJson(), 200));
+ await second;
+ expect(harness.splits.isLoading('parent_1'), isFalse);
+ });
+
+ test('clear() drops a lookup that was still in flight', () async {
+ final response = Completer<http.Response>();
+ final harness = _Harness(handler: (_) => response.future);
+
+ final pending = harness.splits
+ .loadSplit(accessToken: 'token', transactionId: 'parent_1');
+ await Future<void>.delayed(Duration.zero);
+ harness.splits.clear();
+ response.complete(http.Response(_splitJson(), 200));
+ await pending;
+
+ expect(harness.splits.isSplitParent('parent_1'), isFalse);
+ expect(harness.splits.isSplitStatusKnown('parent_1'), isFalse);
+ expect(harness.splits.isLoading('parent_1'), isFalse);
+ });
+ });
+}