The personal finance app for everyone (by everyone)
Ruby
feat(mobile): budgets screen (#4426)
Bhargav Mehtac5e7c05c0163
diff --git a/mobile/lib/l10n/app_en.arb b/mobile/lib/l10n/app_en.arbindex 68187912f4..de26376f33 100644--- a/mobile/lib/l10n/app_en.arb+++ b/mobile/lib/l10n/app_en.arb@@ -974,5 +974,134 @@},"chatConversationStartFailed": "Failed to start conversation. Please try again.",- "@chatConversationStartFailed": { "description": "Fallback snackbar shown when creating a new conversation from the first message fails." }+ "@chatConversationStartFailed": { "description": "Fallback snackbar shown when creating a new conversation from the first message fails." },++ "moreBudgets": "Budgets",+ "@moreBudgets": { "description": "Menu item title for Budgets in the More screen." },++ "moreBudgetsSubtitle": "Budgeted vs. actual spending by category",+ "@moreBudgetsSubtitle": { "description": "Subtitle for the Budgets menu item in the More screen." },++ "budgetsTitle": "Budgets",+ "@budgetsTitle": { "description": "App bar title of the Budgets screen." },++ "budgetsPreviousMonth": "Previous month",+ "@budgetsPreviousMonth": { "description": "Tooltip for the button that shows the previous month's budget." },++ "budgetsNextMonth": "Next month",+ "@budgetsNextMonth": { "description": "Tooltip for the button that shows the next month's budget." },++ "budgetsBudgeted": "Budgeted",+ "@budgetsBudgeted": { "description": "Label for the total amount budgeted for spending this month." },++ "budgetsActual": "Actual",+ "@budgetsActual": { "description": "Label for the amount actually spent this month." },++ "budgetsRemaining": "Remaining",+ "@budgetsRemaining": { "description": "Label for the amount left to spend this month." },++ "budgetsIncome": "Income",+ "@budgetsIncome": { "description": "Label for the month's actual income in the budget summary." },++ "budgetsExpectedIncome": "Expected {amount}",+ "@budgetsExpectedIncome": {+ "description": "Expected income for the month, shown next to actual income.",+ "placeholders": { "amount": { "type": "String" } }+ },++ "budgetsOfAmount": "of {amount}",+ "@budgetsOfAmount": {+ "description": "Budget limit shown after the amount spent in a category, e.g. '$120 of $300'.",+ "placeholders": { "amount": { "type": "String" } }+ },++ "budgetsAmountLeft": "{amount} left",+ "@budgetsAmountLeft": {+ "description": "Amount still available to spend in a category.",+ "placeholders": { "amount": { "type": "String" } }+ },++ "budgetsOverBy": "{amount} over",+ "@budgetsOverBy": {+ "description": "Amount by which a category's spending exceeds its budget.",+ "placeholders": { "amount": { "type": "String" } }+ },++ "budgetsRolledOver": "+{amount} rolled over",+ "@budgetsRolledOver": {+ "description": "Unspent amount carried over from the previous month into this category.",+ "placeholders": { "amount": { "type": "String" } }+ },++ "budgetsSharedBudget": "Shared budget",+ "@budgetsSharedBudget": { "description": "Shown for a subcategory without its own limit that draws from its parent category's budget." },++ "budgetsNoLimit": "No budget",+ "@budgetsNoLimit": { "description": "Shown for a category with spending but no budgeted amount." },++ "budgetsCategoriesTitle": "Categories",+ "@budgetsCategoriesTitle": { "description": "Heading of the per-category budget list." },++ "budgetsFilterOverBudget": "Over budget ({count})",+ "@budgetsFilterOverBudget": {+ "description": "Filter showing only categories that are over budget, with how many there are.",+ "placeholders": { "count": { "type": "int" } }+ },++ "budgetsOverBudget": "Over budget",+ "@budgetsOverBudget": { "description": "Badge on a category that has spent more than its budget." },++ "budgetsNearLimit": "Near limit",+ "@budgetsNearLimit": { "description": "Badge on a category that has spent at least 90% of its budget." },++ "budgetsBudgetNumber": "Budget {number}",+ "@budgetsBudgetNumber": {+ "description": "Label for one of several budgets that exist for the same month (household, personal or shared).",+ "placeholders": { "number": { "type": "int" } }+ },++ "budgetsNoBudgetTitle": "No budget for {month}",+ "@budgetsNoBudgetTitle": {+ "description": "Title shown when the server has no budget for the selected month.",+ "placeholders": { "month": { "type": "String" } }+ },++ "budgetsNoBudgetMessage": "Budgets are created in Sure on the web. Open Budgets there to set one up for this month.",+ "@budgetsNoBudgetMessage": { "description": "Explains how to create a budget when none exists for the selected month." },++ "budgetsNotSetUpMessage": "No spending limits are set for this month yet. Set them up in Sure on the web.",+ "@budgetsNotSetUpMessage": { "description": "Shown when a budget exists for the month but has no amounts set." },++ "budgetsNoCategories": "No budgeted categories or spending this month.",+ "@budgetsNoCategories": { "description": "Shown when no category line has a budget or spending." },++ "budgetsOfflineTitle": "You're offline",+ "@budgetsOfflineTitle": { "description": "Title shown when the budget cannot be loaded without a connection." },++ "budgetsOfflineMessage": "Connect to the internet to load this month's budget.",+ "@budgetsOfflineMessage": { "description": "Shown when offline and the selected month has not been loaded yet." },++ "budgetsOfflineCached": "Offline. Showing the figures loaded earlier.",+ "@budgetsOfflineCached": { "description": "Banner shown when offline and the budget shown was loaded earlier in the session." },++ "budgetsRefreshFailed": "Couldn't refresh. Showing the figures loaded earlier.",+ "@budgetsRefreshFailed": { "description": "Banner shown when refreshing a budget fails but the month loaded earlier is still on screen." },++ "budgetsLoadFailed": "Couldn't load budgets",+ "@budgetsLoadFailed": { "description": "Title shown when loading budgets fails." },++ "budgetsSessionExpired": "Your session has expired. Please sign in again.",+ "@budgetsSessionExpired": { "description": "Shown when the budgets request is rejected as unauthorized." },++ "budgetCategoryTransactionsEmpty": "No transactions in this category for {month}.",+ "@budgetCategoryTransactionsEmpty": {+ "description": "Empty state of a budget category's transaction list.",+ "placeholders": { "month": { "type": "String" } }+ },++ "budgetCategoryTransactionsLoadMore": "Load more",+ "@budgetCategoryTransactionsLoadMore": { "description": "Button that loads the next page of a budget category's transactions." },++ "budgetCategoryTransactionsLoadFailed": "Couldn't load transactions",+ "@budgetCategoryTransactionsLoadFailed": { "description": "Shown when a budget category's transactions fail to load." }}diff --git a/mobile/lib/l10n/app_localizations.dart b/mobile/lib/l10n/app_localizations.dartindex 43404ebe7f..3f63522389 100644--- a/mobile/lib/l10n/app_localizations.dart+++ b/mobile/lib/l10n/app_localizations.dart@@ -63,7 +63,7 @@ import 'app_localizations_sv.dart';/// property.abstract class AppLocalizations {AppLocalizations(String locale)- : localeName = intl.Intl.canonicalizedLocale(locale.toString());+ : localeName = intl.Intl.canonicalizedLocale(locale.toString());final String localeName;@@ -86,11 +86,11 @@ abstract class AppLocalizations {/// of delegates is preferred or required.static const List<LocalizationsDelegate<dynamic>> localizationsDelegates =<LocalizationsDelegate<dynamic>>[- delegate,- GlobalMaterialLocalizations.delegate,- GlobalCupertinoLocalizations.delegate,- GlobalWidgetsLocalizations.delegate,- ];+ delegate,+ GlobalMaterialLocalizations.delegate,+ GlobalCupertinoLocalizations.delegate,+ GlobalWidgetsLocalizations.delegate,+ ];/// A list of this localizations delegate's supported locales.static const List<Locale> supportedLocales = <Locale>[@@ -1915,6 +1915,210 @@ abstract class AppLocalizations {/// In en, this message translates to:/// **'Failed to start conversation. Please try again.'**String get chatConversationStartFailed;++ /// Menu item title for Budgets in the More screen.+ ///+ /// In en, this message translates to:+ /// **'Budgets'**+ String get moreBudgets;++ /// Subtitle for the Budgets menu item in the More screen.+ ///+ /// In en, this message translates to:+ /// **'Budgeted vs. actual spending by category'**+ String get moreBudgetsSubtitle;++ /// App bar title of the Budgets screen.+ ///+ /// In en, this message translates to:+ /// **'Budgets'**+ String get budgetsTitle;++ /// Tooltip for the button that shows the previous month's budget.+ ///+ /// In en, this message translates to:+ /// **'Previous month'**+ String get budgetsPreviousMonth;++ /// Tooltip for the button that shows the next month's budget.+ ///+ /// In en, this message translates to:+ /// **'Next month'**+ String get budgetsNextMonth;++ /// Label for the total amount budgeted for spending this month.+ ///+ /// In en, this message translates to:+ /// **'Budgeted'**+ String get budgetsBudgeted;++ /// Label for the amount actually spent this month.+ ///+ /// In en, this message translates to:+ /// **'Actual'**+ String get budgetsActual;++ /// Label for the amount left to spend this month.+ ///+ /// In en, this message translates to:+ /// **'Remaining'**+ String get budgetsRemaining;++ /// Label for the month's actual income in the budget summary.+ ///+ /// In en, this message translates to:+ /// **'Income'**+ String get budgetsIncome;++ /// Expected income for the month, shown next to actual income.+ ///+ /// In en, this message translates to:+ /// **'Expected {amount}'**+ String budgetsExpectedIncome(String amount);++ /// Budget limit shown after the amount spent in a category, e.g. '$120 of $300'.+ ///+ /// In en, this message translates to:+ /// **'of {amount}'**+ String budgetsOfAmount(String amount);++ /// Amount still available to spend in a category.+ ///+ /// In en, this message translates to:+ /// **'{amount} left'**+ String budgetsAmountLeft(String amount);++ /// Amount by which a category's spending exceeds its budget.+ ///+ /// In en, this message translates to:+ /// **'{amount} over'**+ String budgetsOverBy(String amount);++ /// Unspent amount carried over from the previous month into this category.+ ///+ /// In en, this message translates to:+ /// **'+{amount} rolled over'**+ String budgetsRolledOver(String amount);++ /// Shown for a subcategory without its own limit that draws from its parent category's budget.+ ///+ /// In en, this message translates to:+ /// **'Shared budget'**+ String get budgetsSharedBudget;++ /// Shown for a category with spending but no budgeted amount.+ ///+ /// In en, this message translates to:+ /// **'No budget'**+ String get budgetsNoLimit;++ /// Heading of the per-category budget list.+ ///+ /// In en, this message translates to:+ /// **'Categories'**+ String get budgetsCategoriesTitle;++ /// Filter showing only categories that are over budget, with how many there are.+ ///+ /// In en, this message translates to:+ /// **'Over budget ({count})'**+ String budgetsFilterOverBudget(int count);++ /// Badge on a category that has spent more than its budget.+ ///+ /// In en, this message translates to:+ /// **'Over budget'**+ String get budgetsOverBudget;++ /// Badge on a category that has spent at least 90% of its budget.+ ///+ /// In en, this message translates to:+ /// **'Near limit'**+ String get budgetsNearLimit;++ /// Label for one of several budgets that exist for the same month (household, personal or shared).+ ///+ /// In en, this message translates to:+ /// **'Budget {number}'**+ String budgetsBudgetNumber(int number);++ /// Title shown when the server has no budget for the selected month.+ ///+ /// In en, this message translates to:+ /// **'No budget for {month}'**+ String budgetsNoBudgetTitle(String month);++ /// Explains how to create a budget when none exists for the selected month.+ ///+ /// In en, this message translates to:+ /// **'Budgets are created in Sure on the web. Open Budgets there to set one up for this month.'**+ String get budgetsNoBudgetMessage;++ /// Shown when a budget exists for the month but has no amounts set.+ ///+ /// In en, this message translates to:+ /// **'No spending limits are set for this month yet. Set them up in Sure on the web.'**+ String get budgetsNotSetUpMessage;++ /// Shown when no category line has a budget or spending.+ ///+ /// In en, this message translates to:+ /// **'No budgeted categories or spending this month.'**+ String get budgetsNoCategories;++ /// Title shown when the budget cannot be loaded without a connection.+ ///+ /// In en, this message translates to:+ /// **'You\'re offline'**+ String get budgetsOfflineTitle;++ /// Shown when offline and the selected month has not been loaded yet.+ ///+ /// In en, this message translates to:+ /// **'Connect to the internet to load this month\'s budget.'**+ String get budgetsOfflineMessage;++ /// Banner shown when offline and the budget shown was loaded earlier in the session.+ ///+ /// In en, this message translates to:+ /// **'Offline. Showing the figures loaded earlier.'**+ String get budgetsOfflineCached;++ /// Banner shown when refreshing a budget fails but the month loaded earlier is still on screen.+ ///+ /// In en, this message translates to:+ /// **'Couldn\'t refresh. Showing the figures loaded earlier.'**+ String get budgetsRefreshFailed;++ /// Title shown when loading budgets fails.+ ///+ /// In en, this message translates to:+ /// **'Couldn\'t load budgets'**+ String get budgetsLoadFailed;++ /// Shown when the budgets request is rejected as unauthorized.+ ///+ /// In en, this message translates to:+ /// **'Your session has expired. Please sign in again.'**+ String get budgetsSessionExpired;++ /// Empty state of a budget category's transaction list.+ ///+ /// In en, this message translates to:+ /// **'No transactions in this category for {month}.'**+ String budgetCategoryTransactionsEmpty(String month);++ /// Button that loads the next page of a budget category's transactions.+ ///+ /// In en, this message translates to:+ /// **'Load more'**+ String get budgetCategoryTransactionsLoadMore;++ /// Shown when a budget category's transactions fail to load.+ ///+ /// In en, this message translates to:+ /// **'Couldn\'t load transactions'**+ String get budgetCategoryTransactionsLoadFailed;}class _AppLocalizationsDelegate@@ -1944,8 +2148,9 @@ AppLocalizations lookupAppLocalizations(Locale locale) {}throw FlutterError(- 'AppLocalizations.delegate failed to load unsupported locale "$locale". This is likely '- 'an issue with the localizations generation tool. Please file an issue '- 'on GitHub with a reproducible sample app and the gen-l10n configuration '- 'that was used.');+ 'AppLocalizations.delegate failed to load unsupported locale "$locale". This is likely '+ 'an issue with the localizations generation tool. Please file an issue '+ 'on GitHub with a reproducible sample app and the gen-l10n configuration '+ 'that was used.',+ );}diff --git a/mobile/lib/l10n/app_localizations_en.dart b/mobile/lib/l10n/app_localizations_en.dartindex 9ab333828a..335b255add 100644--- a/mobile/lib/l10n/app_localizations_en.dart+++ b/mobile/lib/l10n/app_localizations_en.dart@@ -1030,4 +1030,132 @@ class AppLocalizationsEn extends AppLocalizations {@overrideString get chatConversationStartFailed =>'Failed to start conversation. Please try again.';++ @override+ String get moreBudgets => 'Budgets';++ @override+ String get moreBudgetsSubtitle => 'Budgeted vs. actual spending by category';++ @override+ String get budgetsTitle => 'Budgets';++ @override+ String get budgetsPreviousMonth => 'Previous month';++ @override+ String get budgetsNextMonth => 'Next month';++ @override+ String get budgetsBudgeted => 'Budgeted';++ @override+ String get budgetsActual => 'Actual';++ @override+ String get budgetsRemaining => 'Remaining';++ @override+ String get budgetsIncome => 'Income';++ @override+ String budgetsExpectedIncome(String amount) {+ return 'Expected $amount';+ }++ @override+ String budgetsOfAmount(String amount) {+ return 'of $amount';+ }++ @override+ String budgetsAmountLeft(String amount) {+ return '$amount left';+ }++ @override+ String budgetsOverBy(String amount) {+ return '$amount over';+ }++ @override+ String budgetsRolledOver(String amount) {+ return '+$amount rolled over';+ }++ @override+ String get budgetsSharedBudget => 'Shared budget';++ @override+ String get budgetsNoLimit => 'No budget';++ @override+ String get budgetsCategoriesTitle => 'Categories';++ @override+ String budgetsFilterOverBudget(int count) {+ return 'Over budget ($count)';+ }++ @override+ String get budgetsOverBudget => 'Over budget';++ @override+ String get budgetsNearLimit => 'Near limit';++ @override+ String budgetsBudgetNumber(int number) {+ return 'Budget $number';+ }++ @override+ String budgetsNoBudgetTitle(String month) {+ return 'No budget for $month';+ }++ @override+ String get budgetsNoBudgetMessage =>+ 'Budgets are created in Sure on the web. Open Budgets there to set one up for this month.';++ @override+ String get budgetsNotSetUpMessage =>+ 'No spending limits are set for this month yet. Set them up in Sure on the web.';++ @override+ String get budgetsNoCategories =>+ 'No budgeted categories or spending this month.';++ @override+ String get budgetsOfflineTitle => 'You\'re offline';++ @override+ String get budgetsOfflineMessage =>+ 'Connect to the internet to load this month\'s budget.';++ @override+ String get budgetsOfflineCached =>+ 'Offline. Showing the figures loaded earlier.';++ @override+ String get budgetsRefreshFailed =>+ 'Couldn\'t refresh. Showing the figures loaded earlier.';++ @override+ String get budgetsLoadFailed => 'Couldn\'t load budgets';++ @override+ String get budgetsSessionExpired =>+ 'Your session has expired. Please sign in again.';++ @override+ String budgetCategoryTransactionsEmpty(String month) {+ return 'No transactions in this category for $month.';+ }++ @override+ String get budgetCategoryTransactionsLoadMore => 'Load more';++ @override+ String get budgetCategoryTransactionsLoadFailed =>+ 'Couldn\'t load transactions';}diff --git a/mobile/lib/l10n/app_localizations_sv.dart b/mobile/lib/l10n/app_localizations_sv.dartindex ec9ac343b1..bf1f703ff0 100644--- a/mobile/lib/l10n/app_localizations_sv.dart+++ b/mobile/lib/l10n/app_localizations_sv.dart@@ -1041,4 +1041,132 @@ class AppLocalizationsSv extends AppLocalizations {@overrideString get chatConversationStartFailed =>'Det gick inte att starta konversationen. Försök igen.';++ @override+ String get moreBudgets => 'Budgetar';++ @override+ String get moreBudgetsSubtitle =>+ 'Budgeterat mot faktiskt utfall per kategori';++ @override+ String get budgetsTitle => 'Budgetar';++ @override+ String get budgetsPreviousMonth => 'Föregående månad';++ @override+ String get budgetsNextMonth => 'Nästa månad';++ @override+ String get budgetsBudgeted => 'Budgeterat';++ @override+ String get budgetsActual => 'Utfall';++ @override+ String get budgetsRemaining => 'Kvar';++ @override+ String get budgetsIncome => 'Inkomster';++ @override+ String budgetsExpectedIncome(String amount) {+ return 'Förväntat $amount';+ }++ @override+ String budgetsOfAmount(String amount) {+ return 'av $amount';+ }++ @override+ String budgetsAmountLeft(String amount) {+ return '$amount kvar';+ }++ @override+ String budgetsOverBy(String amount) {+ return '$amount över';+ }++ @override+ String budgetsRolledOver(String amount) {+ return '+$amount överfört';+ }++ @override+ String get budgetsSharedBudget => 'Delad budget';++ @override+ String get budgetsNoLimit => 'Ingen budget';++ @override+ String get budgetsCategoriesTitle => 'Kategorier';++ @override+ String budgetsFilterOverBudget(int count) {+ return 'Över budget ($count)';+ }++ @override+ String get budgetsOverBudget => 'Över budget';++ @override+ String get budgetsNearLimit => 'Nära gränsen';++ @override+ String budgetsBudgetNumber(int number) {+ return 'Budget $number';+ }++ @override+ String budgetsNoBudgetTitle(String month) {+ return 'Ingen budget för $month';+ }++ @override+ String get budgetsNoBudgetMessage =>+ 'Budgetar skapas i Sure på webben. Öppna Budgetar där för att skapa en för den här månaden.';++ @override+ String get budgetsNotSetUpMessage =>+ 'Inga utgiftsgränser är satta för den här månaden än. Ställ in dem i Sure på webben.';++ @override+ String get budgetsNoCategories =>+ 'Inga budgeterade kategorier eller utgifter den här månaden.';++ @override+ String get budgetsOfflineTitle => 'Du är offline';++ @override+ String get budgetsOfflineMessage =>+ 'Anslut till internet för att läsa in den här månadens budget.';++ @override+ String get budgetsOfflineCached =>+ 'Offline. Visar siffrorna som lästes in tidigare.';++ @override+ String get budgetsRefreshFailed =>+ 'Kunde inte uppdatera. Visar siffrorna som lästes in tidigare.';++ @override+ String get budgetsLoadFailed => 'Kunde inte läsa in budgetar';++ @override+ String get budgetsSessionExpired => 'Din session har gått ut. Logga in igen.';++ @override+ String budgetCategoryTransactionsEmpty(String month) {+ return 'Inga transaktioner i den här kategorin för $month.';+ }++ @override+ String get budgetCategoryTransactionsLoadMore => 'Visa fler';++ @override+ String get budgetCategoryTransactionsLoadFailed =>+ 'Kunde inte läsa in transaktioner';}diff --git a/mobile/lib/l10n/app_sv.arb b/mobile/lib/l10n/app_sv.arbindex 129c5bc475..c601b46d93 100644--- a/mobile/lib/l10n/app_sv.arb+++ b/mobile/lib/l10n/app_sv.arb@@ -302,5 +302,39 @@"chatListMinutesAgo": "för {minutes} min sedan","chatListHoursAgo": "för {hours} tim sedan","chatListDaysAgo": "för {days} d sedan",- "chatConversationStartFailed": "Det gick inte att starta konversationen. Försök igen."+ "chatConversationStartFailed": "Det gick inte att starta konversationen. Försök igen.",+ "moreBudgets": "Budgetar",+ "moreBudgetsSubtitle": "Budgeterat mot faktiskt utfall per kategori",+ "budgetsTitle": "Budgetar",+ "budgetsPreviousMonth": "Föregående månad",+ "budgetsNextMonth": "Nästa månad",+ "budgetsBudgeted": "Budgeterat",+ "budgetsActual": "Utfall",+ "budgetsRemaining": "Kvar",+ "budgetsIncome": "Inkomster",+ "budgetsExpectedIncome": "Förväntat {amount}",+ "budgetsOfAmount": "av {amount}",+ "budgetsAmountLeft": "{amount} kvar",+ "budgetsOverBy": "{amount} över",+ "budgetsRolledOver": "+{amount} överfört",+ "budgetsSharedBudget": "Delad budget",+ "budgetsNoLimit": "Ingen budget",+ "budgetsCategoriesTitle": "Kategorier",+ "budgetsFilterOverBudget": "Över budget ({count})",+ "budgetsOverBudget": "Över budget",+ "budgetsNearLimit": "Nära gränsen",+ "budgetsBudgetNumber": "Budget {number}",+ "budgetsNoBudgetTitle": "Ingen budget för {month}",+ "budgetsNoBudgetMessage": "Budgetar skapas i Sure på webben. Öppna Budgetar där för att skapa en för den här månaden.",+ "budgetsNotSetUpMessage": "Inga utgiftsgränser är satta för den här månaden än. Ställ in dem i Sure på webben.",+ "budgetsNoCategories": "Inga budgeterade kategorier eller utgifter den här månaden.",+ "budgetsOfflineTitle": "Du är offline",+ "budgetsOfflineMessage": "Anslut till internet för att läsa in den här månadens budget.",+ "budgetsOfflineCached": "Offline. Visar siffrorna som lästes in tidigare.",+ "budgetsRefreshFailed": "Kunde inte uppdatera. Visar siffrorna som lästes in tidigare.",+ "budgetsLoadFailed": "Kunde inte läsa in budgetar",+ "budgetsSessionExpired": "Din session har gått ut. Logga in igen.",+ "budgetCategoryTransactionsEmpty": "Inga transaktioner i den här kategorin för {month}.",+ "budgetCategoryTransactionsLoadMore": "Visa fler",+ "budgetCategoryTransactionsLoadFailed": "Kunde inte läsa in transaktioner"}diff --git a/mobile/lib/models/budget.dart b/mobile/lib/models/budget.dartnew file mode 100644index 0000000000..eca1d4cfaa--- /dev/null+++ b/mobile/lib/models/budget.dart@@ -0,0 +1,386 @@+/// A monthly budget as returned by `GET /api/v1/budgets` and+/// `GET /api/v1/budgets/:id`.+///+/// Money fields come in pairs: a server-formatted string (already localized+/// with the budget currency, e.g. `$1,234.56`) and the same value in minor+/// units (`*_cents`). The strings are what we render, so formatting stays in+/// lockstep with the web app; the cents drive comparisons and progress bars.+///+/// The index endpoint omits the derived amounts (actual spending, available to+/// spend, ...), so those are nullable and only populated from the show+/// endpoint.+class Budget {+ const Budget({+ required this.id,+ required this.startDate,+ required this.endDate,+ required this.name,+ required this.currency,+ required this.initialized,+ required this.current,+ this.budgetedSpending,+ this.budgetedSpendingCents,+ this.expectedIncome,+ this.expectedIncomeCents,+ this.allocatedSpending,+ this.allocatedSpendingCents,+ this.actualSpending,+ this.actualSpendingCents,+ this.actualIncome,+ this.actualIncomeCents,+ this.availableToSpend,+ this.availableToSpendCents,+ this.availableToAllocate,+ this.availableToAllocateCents,+ });++ final String id;+ final DateTime startDate;+ final DateTime endDate;+ final String name;+ final String currency;+ final bool initialized;+ final bool current;++ final String? budgetedSpending;+ final int? budgetedSpendingCents;+ final String? expectedIncome;+ final int? expectedIncomeCents;+ final String? allocatedSpending;+ final int? allocatedSpendingCents;++ final String? actualSpending;+ final int? actualSpendingCents;+ final String? actualIncome;+ final int? actualIncomeCents;+ final String? availableToSpend;+ final int? availableToSpendCents;+ final String? availableToAllocate;+ final int? availableToAllocateCents;++ /// Whether this record carries the derived amounts (show endpoint).+ bool get hasDerivedAmounts => actualSpendingCents != null;++ bool get isOverBudget => (availableToSpendCents ?? 0) < 0;++ /// Same rule as [BudgetCategory.isNearLimit]: 90% or more spent, not over.+ bool get isNearLimit =>+ !isOverBudget && spentFraction >= BudgetCategory.nearLimitFraction;++ /// Share of the budget already spent, 0..∞ (1.0 == 100%).+ ///+ /// `available_to_spend` is the budget minus actual spending (Rails+ /// `Budget#available_to_spend`; rollover only applies per category), so+ /// `actual + available` reconstructs the budget.+ double get spentFraction {+ final actual = actualSpendingCents ?? 0;+ final available = availableToSpendCents ?? 0;+ return spentFractionFor(actual: actual, total: actual + available);+ }++ factory Budget.fromJson(Map<String, dynamic> json) {+ return Budget(+ id: json['id']?.toString() ?? '',+ startDate: _parseDate(json['start_date']),+ endDate: _parseDate(json['end_date']),+ name: json['name']?.toString() ?? '',+ currency: json['currency']?.toString() ?? '',+ initialized: json['initialized'] == true,+ current: json['current'] == true,+ budgetedSpending: _string(json['budgeted_spending']),+ budgetedSpendingCents: _int(json['budgeted_spending_cents']),+ expectedIncome: _string(json['expected_income']),+ expectedIncomeCents: _int(json['expected_income_cents']),+ allocatedSpending: _string(json['allocated_spending']),+ allocatedSpendingCents: _int(json['allocated_spending_cents']),+ actualSpending: _string(json['actual_spending']),+ actualSpendingCents: _int(json['actual_spending_cents']),+ actualIncome: _string(json['actual_income']),+ actualIncomeCents: _int(json['actual_income_cents']),+ availableToSpend: _string(json['available_to_spend']),+ availableToSpendCents: _int(json['available_to_spend_cents']),+ availableToAllocate: _string(json['available_to_allocate']),+ availableToAllocateCents: _int(json['available_to_allocate_cents']),+ );+ }+}++/// The category a [BudgetCategory] belongs to, as embedded in the API payload.+class BudgetCategoryInfo {+ const BudgetCategoryInfo({+ required this.id,+ required this.name,+ this.color,+ this.lucideIcon,+ this.parentId,+ });++ final String id;+ final String name;+ final String? color;+ final String? lucideIcon;+ final String? parentId;++ factory BudgetCategoryInfo.fromJson(Map<String, dynamic> json) {+ final parentId = json['parent_id']?.toString();+ return BudgetCategoryInfo(+ id: json['id']?.toString() ?? '',+ name: json['name']?.toString() ?? '',+ color: _string(json['color']),+ lucideIcon: _string(json['lucide_icon']),+ parentId: (parentId == null || parentId.isEmpty) ? null : parentId,+ );+ }+}++/// One category line of a budget, from `GET /api/v1/budget_categories[/:id]`.+///+/// Mirrors the classification helpers on the Rails `BudgetCategory` model+/// (`budgeted?`, `over_budget?`, `near_limit?`, `visible_on_track?`) using only+/// the fields the API exposes.+class BudgetCategory {+ const BudgetCategory({+ required this.id,+ required this.budgetId,+ required this.currency,+ required this.subcategory,+ required this.inheritsParentBudget,+ required this.rolloverEnabled,+ required this.category,+ this.budgetedSpending,+ this.budgetedSpendingCents,+ this.displayBudgetedSpending,+ this.displayBudgetedSpendingCents,+ this.actualSpending,+ this.actualSpendingCents,+ this.rolledOverAmount,+ this.rolledOverAmountCents,+ this.availableToSpend,+ this.availableToSpendCents,+ this.sharedBudgetCents,+ });++ final String id;+ final String budgetId;+ final String currency;+ final bool subcategory;+ final bool inheritsParentBudget;+ final bool rolloverEnabled;+ final BudgetCategoryInfo category;++ final String? budgetedSpending;+ final int? budgetedSpendingCents;+ final String? displayBudgetedSpending;+ final int? displayBudgetedSpendingCents;++ final String? actualSpending;+ final int? actualSpendingCents;+ final String? rolledOverAmount;+ final int? rolledOverAmountCents;+ final String? availableToSpend;+ final int? availableToSpendCents;++ /// For a subcategory sharing its parent's budget: the part of the parent's+ /// budget (plus rollover) not reserved by sibling subcategories with their+ /// own allocation. Set by [BudgetCategoryGroup.build].+ final int? sharedBudgetCents;++ /// A copy carrying [sharedBudgetCents].+ BudgetCategory withSharedBudgetCents(int cents) => BudgetCategory(+ id: id,+ budgetId: budgetId,+ currency: currency,+ subcategory: subcategory,+ inheritsParentBudget: inheritsParentBudget,+ rolloverEnabled: rolloverEnabled,+ category: category,+ budgetedSpending: budgetedSpending,+ budgetedSpendingCents: budgetedSpendingCents,+ displayBudgetedSpending: displayBudgetedSpending,+ displayBudgetedSpendingCents: displayBudgetedSpendingCents,+ actualSpending: actualSpending,+ actualSpendingCents: actualSpendingCents,+ rolledOverAmount: rolledOverAmount,+ rolledOverAmountCents: rolledOverAmountCents,+ availableToSpend: availableToSpend,+ availableToSpendCents: availableToSpendCents,+ sharedBudgetCents: cents,+ );++ String get name => category.name;+ String? get parentCategoryId => category.parentId;++ /// Whether this record carries the derived amounts (show endpoint).+ bool get hasDerivedAmounts => actualSpendingCents != null;++ int get _actual => actualSpendingCents ?? 0;+ int get _available => availableToSpendCents ?? 0;++ /// The month's allocation plus any carried-over amount — "is there money in+ /// this envelope" (web: `budgeted?`).+ int get effectiveBudgetCents =>+ (displayBudgetedSpendingCents ?? 0) + (rolledOverAmountCents ?? 0);++ bool get isBudgeted => effectiveBudgetCents > 0;++ /// Over budget: either spending against no budget at all, or a negative+ /// amount left (web: `any_over_budget?`). Subcategories that share their+ /// parent's budget never go negative on their own; the parent does.+ bool get isOverBudget {+ if (!isBudgeted) return _actual > 0;+ return _available < 0;+ }++ /// Share spent, 0..∞ (1.0 == 100%).+ double get spentFraction {+ if (inheritsParentBudget) {+ // The API clamps a shared child's available amount at zero, so measure+ // its spending against the shared pool it draws from: the parent's+ // budget less ring-fenced siblings (web: `percent_of_budget_spent`).+ return spentFractionFor(+ actual: _actual,+ total: sharedBudgetCents ?? effectiveBudgetCents,+ );+ }+ // For everything else `available = budget + rollover - actual`.+ return spentFractionFor(actual: _actual, total: _actual + _available);+ }++ /// Spent share at which a line counts as near its limit (web: 90%).+ static const double nearLimitFraction = 0.9;++ /// Within 10% of the limit but not over it (web: `near_limit?`).+ bool get isNearLimit => !isOverBudget && spentFraction >= nearLimitFraction;++ /// Whether the web budget page would show this line at all: budgeted lines+ /// (shared subcategories only once they have spending) and anything with+ /// spending.+ bool get isVisible {+ if (_actual > 0) return true;+ if (!isBudgeted) return false;+ return !inheritsParentBudget;+ }++ factory BudgetCategory.fromJson(Map<String, dynamic> json) {+ final categoryJson = json['category'];+ return BudgetCategory(+ id: json['id']?.toString() ?? '',+ budgetId: json['budget_id']?.toString() ?? '',+ currency: json['currency']?.toString() ?? '',+ subcategory: json['subcategory'] == true,+ inheritsParentBudget: json['inherits_parent_budget'] == true,+ rolloverEnabled: json['rollover_enabled'] == true,+ category: categoryJson is Map+ ? BudgetCategoryInfo.fromJson(categoryJson.cast<String, dynamic>())+ : const BudgetCategoryInfo(id: '', name: ''),+ budgetedSpending: _string(json['budgeted_spending']),+ budgetedSpendingCents: _int(json['budgeted_spending_cents']),+ displayBudgetedSpending: _string(json['display_budgeted_spending']),+ displayBudgetedSpendingCents: _int(+ json['display_budgeted_spending_cents'],+ ),+ actualSpending: _string(json['actual_spending']),+ actualSpendingCents: _int(json['actual_spending_cents']),+ rolledOverAmount: _string(json['rolled_over_amount']),+ rolledOverAmountCents: _int(json['rolled_over_amount_cents']),+ availableToSpend: _string(json['available_to_spend']),+ availableToSpendCents: _int(json['available_to_spend_cents']),+ );+ }+}++/// A parent budget category with its subcategories, in display order.+class BudgetCategoryGroup {+ const BudgetCategoryGroup({required this.parent, required this.children});++ final BudgetCategory parent;+ final List<BudgetCategory> children;++ /// Every category id whose transactions roll up into [parent]'s actual+ /// spending (the parent and all of its subcategories).+ List<String> get categoryIds => [+ parent.category.id,+ ...children.map((c) => c.category.id),+ ];++ bool get hasOverBudget =>+ parent.isOverBudget || children.any((c) => c.isOverBudget);++ /// Groups [categories] by parent, keeping the server order (name ASC) and+ /// placing subcategories whose parent is not in the list as their own group.+ static List<BudgetCategoryGroup> build(List<BudgetCategory> categories) {+ final byCategoryId = {for (final c in categories) c.category.id: c};+ final childrenByParent = <String, List<BudgetCategory>>{};+ final roots = <BudgetCategory>[];++ for (final c in categories) {+ final parentId = c.parentCategoryId;+ if (parentId != null && byCategoryId.containsKey(parentId)) {+ childrenByParent.putIfAbsent(parentId, () => []).add(c);+ } else {+ roots.add(c);+ }+ }++ return [+ for (final root in roots)+ BudgetCategoryGroup(+ parent: root,+ children: _withSharedBudgets(+ root,+ childrenByParent[root.category.id] ?? const [],+ ),+ ),+ ];+ }++ static List<BudgetCategory> _withSharedBudgets(+ BudgetCategory parent,+ List<BudgetCategory> children,+ ) {+ if (!children.any((c) => c.inheritsParentBudget)) return children;+ final ringFenced = children+ .where((c) => !c.inheritsParentBudget)+ .fold<int>(0, (sum, c) => sum + (c.budgetedSpendingCents ?? 0));+ // The API's parent rollover is Rails' display_rolled_over_amount: the+ // parent's own plus its ring-fenced children's. The shared pool only+ // gets the parent's own, so take the ring-fenced rollovers back out.+ final ringFencedRollover = children+ .where((c) => !c.inheritsParentBudget)+ .fold<int>(0, (sum, c) => sum + (c.rolledOverAmountCents ?? 0));+ final pool = (parent.budgetedSpendingCents ?? 0) ++ ((parent.rolledOverAmountCents ?? 0) - ringFencedRollover) -+ ringFenced;+ final shared = pool < 0 ? 0 : pool;+ return [+ for (final c in children)+ c.inheritsParentBudget ? c.withSharedBudgetCents(shared) : c,+ ];+ }+}++/// Fraction spent of [total], with the web app's zero-budget rules: nothing+/// budgeted and nothing spent is 0%, spending against nothing is 100%.+double spentFractionFor({required int actual, required int total}) {+ if (total <= 0) return actual > 0 ? 1.0 : 0.0;+ if (actual <= 0) return 0.0;+ return actual / total;+}++DateTime _parseDate(dynamic value) {+ return DateTime.tryParse(value?.toString() ?? '') ??+ DateTime.fromMillisecondsSinceEpoch(0);+}++String? _string(dynamic value) {+ if (value == null) return null;+ final s = value.toString();+ return s.isEmpty ? null : s;+}++int? _int(dynamic value) {+ if (value is int) return value;+ if (value is num) return value.round();+ if (value is String) return int.tryParse(value);+ return null;+}diff --git a/mobile/lib/providers/budgets_provider.dart b/mobile/lib/providers/budgets_provider.dartnew file mode 100644index 0000000000..d304fff2c4--- /dev/null+++ b/mobile/lib/providers/budgets_provider.dart@@ -0,0 +1,491 @@+import 'package:flutter/foundation.dart';++import '../models/budget.dart';+import '../services/budgets_service.dart';+import '../services/log_service.dart';++/// Why a month could not be shown.+enum BudgetsLoadError { offline, unauthorized, failed }++/// State for the Budgets screen: the selected month, the budget(s) the server+/// has for it, and each category line with its actual spending.+///+/// The budgets API is read-only and its list endpoints leave out actual+/// amounts, so a month is assembled from the budget list (to find the month's+/// budget), the budget's show endpoint (totals) and one show request per+/// budget category (actual / remaining). Months already loaded in this session+/// are kept in memory, so flipping back is instant and still works offline.+class BudgetsProvider with ChangeNotifier {+ BudgetsProvider({+ BudgetsService? service,+ DateTime Function()? clock,+ bool Function()? isOffline,+ }) : _service = service ?? BudgetsService(),+ _clock = clock ?? DateTime.now,+ _isOffline = isOffline ?? (() => false) {+ _month = _firstOfMonth(_clock());+ }++ final BudgetsService _service;+ final DateTime Function() _clock;+ final bool Function() _isOffline;+ final LogService _log = LogService.instance;++ /// Concurrent per-category requests while assembling a month.+ static const int _categoryConcurrency = 6;+ static const int _perPage = 100;++ /// Safety stop for a server that keeps reporting more pages (10,000 lines).+ static const int _maxCategoryPages = 100;++ late DateTime _month;+ final Map<String, _MonthData> _cache = {};+ final Map<String, String> _selectedBudgetByMonth = {};+ bool _isLoading = false;+ BudgetsLoadError? _error;+ bool _showingCachedWhileOffline = false;+ int _generation = 0;+ bool _isDisposed = false;++ /// First month of the budget period that contains today. For a family whose+ /// month starts on, say, the 15th, on October 10 that is September. Starts+ /// as the calendar month and is corrected by the first successful load.+ late DateTime _currentPeriodMonth = _firstOfMonth(_clock());+ bool _currentPeriodResolved = false;++ /// First day of the month being shown.+ DateTime get month => _month;+ bool get isLoading => _isLoading;+ BudgetsLoadError? get error => _error;++ /// True when the device is offline and the month shown came from memory.+ bool get showingCachedWhileOffline => _showingCachedWhileOffline;++ _MonthData? get _current => _cache[_monthKey(_month)];++ /// Whether the server returned a budget list for the month (possibly empty).+ bool get hasLoadedMonth => _current != null;++ /// A refresh failed but an earlier load of this month is still held, so the+ /// screen can keep showing it instead of replacing it with an error page.+ bool get refreshFailed => _error == BudgetsLoadError.failed && hasLoadedMonth;++ /// All budgets visible to the user for this month: the household budget+ /// plus any personal or shared ones.+ List<Budget> get monthBudgets => _current?.budgets ?? const [];++ Budget? get budget => _current?.selected;++ List<BudgetCategory> get categories => _current?.categories ?? const [];++ /// True while the selected budget is not initialized yet: the web page then+ /// shows every category rather than only the budgeted ones.+ bool get showsAllCategories => budget != null && !budget!.initialized;++ List<BudgetCategory>? _visibleGroupsSource;+ bool? _visibleGroupsShowAll;+ List<BudgetCategoryGroup> _visibleGroups = const [];++ /// Parent categories with their subcategories, limited to the lines the web+ /// budget page shows (budgeted, or with spending). Rebuilt only when the+ /// month's categories change.+ List<BudgetCategoryGroup> get visibleGroups {+ final source = categories;+ if (identical(source, _visibleGroupsSource) &&+ _visibleGroupsShowAll == showsAllCategories) {+ return _visibleGroups;+ }+ _visibleGroupsSource = source;+ _visibleGroupsShowAll = showsAllCategories;+ return _visibleGroups = _buildVisibleGroups();+ }++ List<BudgetCategoryGroup> _buildVisibleGroups() {+ final groups = BudgetCategoryGroup.build(categories);+ // Web: `budget.initialized? ? visible_on_track? : true`. A budget that+ // hasn't been set up yet lists every category so it can be configured.+ if (showsAllCategories) return groups;+ final visible = <BudgetCategoryGroup>[];+ for (final group in groups) {+ final children = group.children.where((c) => c.isVisible).toList();+ if (group.parent.isVisible || children.isNotEmpty) {+ visible.add(+ BudgetCategoryGroup(parent: group.parent, children: children),+ );+ }+ }+ return visible;+ }++ /// Number of visible category lines (parents and subcategories) that are+ /// over budget.+ int get overBudgetCount {+ var count = 0;+ for (final group in visibleGroups) {+ if (group.parent.isOverBudget) count++;+ count += group.children.where((c) => c.isOverBudget).length;+ }+ return count;+ }++ /// The server accepts budgets up to two years past the current period+ /// (web: `Budget.latest_valid_budget_start_date`), so planned future months+ /// stay reachable.+ bool get canGoNext => _month.isBefore(+ DateTime(_currentPeriodMonth.year + 2, _currentPeriodMonth.month),+ );++ void previousMonth() => _setMonth(DateTime(_month.year, _month.month - 1));++ void nextMonth() {+ if (canGoNext) _setMonth(DateTime(_month.year, _month.month + 1));+ }++ void _setMonth(DateTime month) {+ // A load still running for the previous month must not clear the spinner+ // or set an error on the month now shown (its result is still cached+ // under its own month).+ _generation++;+ _isLoading = false;+ _month = _firstOfMonth(month);+ _error = null;+ _showingCachedWhileOffline = false;+ notifyListeners();+ }++ /// Switch between budgets when the month has more than one.+ Future<void> selectBudget({+ required String accessToken,+ required String budgetId,+ }) async {+ final key = _monthKey(_month);+ if (_cache[key]?.selected?.id == budgetId) return;+ _selectedBudgetByMonth[key] = budgetId;+ // The month's budget list is already known; only the chosen budget's+ // detail and categories need fetching.+ await _loadMonth(+ accessToken: accessToken,+ forceRefresh: true,+ knownBudgets: _cache[key]?.budgets,+ knownBudgetsMonthKey: key,+ );+ }++ /// Shows the session-expired state, e.g. when no access token is available.+ void markUnauthorized() {+ _generation++;+ _isLoading = false;+ _error = BudgetsLoadError.unauthorized;+ _showingCachedWhileOffline = false;+ notifyListeners();+ }++ /// Loads the selected month. Uses the in-memory copy unless [forceRefresh].+ Future<void> loadMonth({+ required String accessToken,+ bool forceRefresh = false,+ }) =>+ _loadMonth(accessToken: accessToken, forceRefresh: forceRefresh);++ Future<void> _loadMonth({+ required String accessToken,+ bool forceRefresh = false,+ List<Budget>? knownBudgets,+ String? knownBudgetsMonthKey,+ }) async {+ if (!_currentPeriodResolved && !_isOffline()) {+ // Show the spinner while the current period resolves; every branch+ // below resets the flag or re-sets it for the month fetch.+ _isLoading = true;+ _error = null;+ notifyListeners();+ await _resolveCurrentPeriod(accessToken);+ }+ final key = _monthKey(_month);+ final month = _month;+ final generation = ++_generation;+ // Resolving the current period above can move [_month]; a budget list+ // captured for another month must not be reused for this one.+ if (knownBudgetsMonthKey != key) knownBudgets = null;++ if (_isOffline()) {+ _showingCachedWhileOffline = _cache.containsKey(key);+ _error = _showingCachedWhileOffline ? null : BudgetsLoadError.offline;+ _isLoading = false;+ notifyListeners();+ return;+ }++ if (!forceRefresh && _cache.containsKey(key)) {+ // A superseded request for another month can't clear this any more.+ _isLoading = false;+ _showingCachedWhileOffline = false;+ _error = null;+ notifyListeners();+ return;+ }++ _isLoading = true;+ _error = null;+ _showingCachedWhileOffline = false;+ notifyListeners();++ try {+ final data = await _fetchMonth(+ accessToken,+ month,+ knownBudgets: knownBudgets,+ );+ if (_isDisposed) return;+ if (generation != _generation) {+ // Superseded (the user moved to another month). The data is complete+ // for its own month, so keep it unless a newer load already did; the+ // UI state belongs to the latest load.+ _cache.putIfAbsent(key, () => data);+ return;+ }+ _cache[key] = data;+ _log.info(+ 'BudgetsProvider',+ 'Loaded ${data.budgets.length} budget(s), '+ '${data.categories.length} categories for $key',+ );+ } on _BudgetsFetchException catch (e) {+ if (generation != _generation) return;+ // The raw error (server message, network exception text) is logged,+ // not shown: the screen shows its own localized failure message.+ _error = e.error;+ _log.error('BudgetsProvider', 'Failed to load budgets for $key: $e');+ } catch (e) {+ if (generation != _generation) return;+ _error = BudgetsLoadError.failed;+ _log.error('BudgetsProvider', 'Exception loading budgets for $key: $e');+ } finally {+ if (generation == _generation) {+ _isLoading = false;+ notifyListeners();+ }+ }+ }++ /// Finds the budget whose period contains today and, if the user hasn't+ /// navigated yet, opens on it. Without one (no budget yet, or a failed+ /// request) the screen stays on the calendar month.+ Future<void> _resolveCurrentPeriod(String accessToken) async {+ final today = _clock();+ final day = DateTime(today.year, today.month, today.day);+ final initialMonth = _firstOfMonth(today);+ try {+ final result = await _service.getBudgets(+ accessToken: accessToken,+ startDate: DateTime(initialMonth.year, initialMonth.month - 1),+ endDate: DateTime(initialMonth.year, initialMonth.month + 2, 0),+ perPage: _perPage,+ );+ if (result['success'] != true) return;+ _currentPeriodResolved = true;+ final budgets = result['budgets'] as List<Budget>;+ // The server knows the family's date (`current`); the device's+ // calendar can be a day off near a period boundary. The local date+ // is only a fallback for servers that don't send the flag.+ Budget? current;+ for (final b in budgets) {+ if (b.current) {+ current = b;+ break;+ }+ }+ if (current == null) {+ for (final b in budgets) {+ if (!b.startDate.isAfter(day) && !b.endDate.isBefore(day)) {+ current = b;+ break;+ }+ }+ }+ if (current != null) {+ _currentPeriodMonth = _firstOfMonth(current.startDate);+ if (_month == initialMonth) _month = _currentPeriodMonth;+ }+ } catch (e) {+ _log.error('BudgetsProvider', 'Could not resolve current period: $e');+ }+ }++ Future<_MonthData> _fetchMonth(+ String accessToken,+ DateTime month, {+ List<Budget>? knownBudgets,+ }) async {+ if (knownBudgets != null) {+ return _fetchSelected(accessToken, month, knownBudgets);+ }+ // A family with a custom month start has budgets that begin mid-month and+ // end in the next one, so widen the window and match on the start month.+ final listResult = await _service.getBudgets(+ accessToken: accessToken,+ startDate: month,+ endDate: DateTime(month.year, month.month + 2, 0),+ perPage: _perPage,+ );+ _throwIfFailed(listResult);++ final budgets = (listResult['budgets'] as List<Budget>)+ .where(+ (b) =>+ b.startDate.year == month.year &&+ b.startDate.month == month.month,+ )+ .toList();++ return _fetchSelected(accessToken, month, budgets);+ }++ Future<_MonthData> _fetchSelected(+ String accessToken,+ DateTime month,+ List<Budget> budgets,+ ) async {+ if (budgets.isEmpty) {+ return _MonthData(budgets: budgets);+ }++ final key = _monthKey(month);+ final preferredId = _selectedBudgetByMonth[key];+ final summary = budgets.firstWhere(+ (b) => b.id == preferredId,+ orElse: () => budgets.first,+ );++ final results = await Future.wait([+ _service.getBudget(accessToken: accessToken, id: summary.id),+ _fetchAllCategories(accessToken, summary.id),+ ]);++ final budgetResult = results[0] as Map<String, dynamic>;+ _throwIfFailed(budgetResult);+ final detailed = budgetResult['budget'] as Budget;++ final indexCategories = results[1] as List<BudgetCategory>;+ final categories = await _withDerivedAmounts(accessToken, indexCategories);++ return _MonthData(+ budgets: budgets,+ selected: detailed,+ categories: categories,+ );+ }++ Future<List<BudgetCategory>> _fetchAllCategories(+ String accessToken,+ String budgetId,+ ) async {+ final all = <BudgetCategory>[];+ var page = 1;+ while (true) {+ final result = await _service.getBudgetCategories(+ accessToken: accessToken,+ budgetId: budgetId,+ page: page,+ perPage: _perPage,+ );+ _throwIfFailed(result);+ all.addAll(result['budget_categories'] as List<BudgetCategory>);++ final pagination = result['pagination'] as Map<String, dynamic>?;+ final totalPages = (pagination?['total_pages'] as num?)?.toInt() ?? 1;+ if (page >= totalPages) break;+ if (page >= _maxCategoryPages) {+ // Never cache a truncated month as if it were complete.+ throw const _BudgetsFetchException(+ BudgetsLoadError.failed,+ 'too many budget category pages',+ );+ }+ page++;+ }+ return all;+ }++ /// Replaces each index record with its show record (which carries actual+ /// spending). A line whose detail record is gone (404) keeps its budgeted+ /// amount; any other failure (401, network, server error) fails the month,+ /// so a partial month is never cached as complete.+ Future<List<BudgetCategory>> _withDerivedAmounts(+ String accessToken,+ List<BudgetCategory> categories,+ ) async {+ final detailed = List<BudgetCategory>.of(categories);+ for (var i = 0; i < categories.length; i += _categoryConcurrency) {+ final end = (i + _categoryConcurrency).clamp(0, categories.length);+ final batch = await Future.wait([+ for (var j = i; j < end; j++)+ _service.getBudgetCategory(+ accessToken: accessToken,+ id: categories[j].id,+ ),+ ]);+ for (var k = 0; k < batch.length; k++) {+ final result = batch[k];+ if (result['success'] == true) {+ detailed[i + k] = result['budget_category'] as BudgetCategory;+ } else if (result['error'] != 'not_found') {+ _throwIfFailed(result);+ }+ }+ }+ return detailed;+ }++ void _throwIfFailed(Map<String, dynamic> result) {+ if (result['success'] == true) return;+ final error = result['error']?.toString();+ throw _BudgetsFetchException(+ error == 'unauthorized'+ ? BudgetsLoadError.unauthorized+ : BudgetsLoadError.failed,+ error == 'unauthorized' ? null : error,+ );+ }++ @override+ void notifyListeners() {+ // A month load can complete after the owning screen disposed this.+ if (!_isDisposed) super.notifyListeners();+ }++ @override+ void dispose() {+ _isDisposed = true;+ _generation++;+ super.dispose();+ }++ static DateTime _firstOfMonth(DateTime date) =>+ DateTime(date.year, date.month);++ static String _monthKey(DateTime date) =>+ '${date.year}-${date.month.toString().padLeft(2, '0')}';+}++class _MonthData {+ const _MonthData({+ required this.budgets,+ this.selected,+ this.categories = const [],+ });++ final List<Budget> budgets;+ final Budget? selected;+ final List<BudgetCategory> categories;+}++class _BudgetsFetchException implements Exception {+ const _BudgetsFetchException(this.error, this.message);++ final BudgetsLoadError error;+ final String? message;++ @override+ String toString() => 'BudgetsFetchException($error, $message)';+}diff --git a/mobile/lib/screens/budget_category_transactions_screen.dart b/mobile/lib/screens/budget_category_transactions_screen.dartnew file mode 100644index 0000000000..984ae13b25--- /dev/null+++ b/mobile/lib/screens/budget_category_transactions_screen.dart@@ -0,0 +1,310 @@+import 'package:flutter/material.dart';+import 'package:intl/intl.dart';+import 'package:provider/provider.dart';++import '../l10n/app_localizations.dart';+import '../models/account.dart';+import '../models/transaction.dart';+import '../providers/accounts_provider.dart';+import '../providers/auth_provider.dart';+import '../providers/privacy_provider.dart';+import '../services/budgets_service.dart';+import '../services/transactions_service.dart';+import '../theme/sure_colors.dart';+import '../theme/sure_spacing.dart';+import '../theme/sure_tokens.dart';+import '../utils/money_masker.dart';+import '../widgets/money_text.dart';+import '../widgets/sure_button.dart';++/// Transactions behind one budget line: the category (and, for a parent, its+/// subcategories) within the budget's date range, newest first, paged from+/// `GET /api/v1/transactions` with `category_ids[]`, `start_date` and+/// `end_date`.+class BudgetCategoryTransactionsScreen extends StatefulWidget {+ const BudgetCategoryTransactionsScreen({+ super.key,+ required this.title,+ required this.periodLabel,+ required this.categoryIds,+ required this.startDate,+ required this.endDate,+ this.service,+ this.accessTokenLoader,+ });++ final String title;+ final String periodLabel;+ final List<String> categoryIds;+ final DateTime startDate;+ final DateTime endDate;++ /// Injected for tests.+ final TransactionsService? service;+ final Future<String?> Function()? accessTokenLoader;++ @override+ State<BudgetCategoryTransactionsScreen> createState() =>+ _BudgetCategoryTransactionsScreenState();+}++class _BudgetCategoryTransactionsScreenState+ extends State<BudgetCategoryTransactionsScreen> {+ static const int _perPage = 50;++ late final TransactionsService _service =+ widget.service ?? TransactionsService();+ final List<Transaction> _transactions = [];+ int _page = 0;+ int _totalPages = 1;+ bool _loading = false;+ bool _failed = false;++ /// Whether the request that failed was a reload from page one, so its retry+ /// repeats it instead of appending the next page to stale rows.+ bool _failedWasReset = false;++ bool get _hasMore => _page < _totalPages;++ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) _loadPage(reset: true);+ });+ }++ Future<String?> _accessToken() {+ final loader = widget.accessTokenLoader;+ if (loader != null) return loader();+ return context.read<AuthProvider>().getValidAccessToken();+ }++ Future<void> _loadPage({bool reset = false}) async {+ if (_loading) return;+ setState(() {+ _loading = true;+ _failed = false;+ });++ final token = await _accessToken();+ if (!mounted) return;+ if (token == null) {+ setState(() {+ _loading = false;+ _failed = true;+ _failedWasReset = reset;+ });+ return;+ }++ final nextPage = reset ? 1 : _page + 1;+ final result = await _service.getTransactions(+ accessToken: token,+ categoryIds: widget.categoryIds,+ startDate: BudgetsService.formatApiDate(widget.startDate),+ endDate: BudgetsService.formatApiDate(widget.endDate),+ page: nextPage,+ perPage: _perPage,+ );+ if (!mounted) return;++ setState(() {+ _loading = false;+ if (result['success'] == true) {+ if (reset) _transactions.clear();+ _transactions.addAll(result['transactions'] as List<Transaction>);+ _page = nextPage;+ final pagination = result['pagination'];+ _totalPages = pagination is Map+ ? (pagination['total_pages'] as num?)?.toInt() ?? nextPage+ : nextPage;+ } else {+ _failed = true;+ _failedWasReset = reset;+ }+ });+ }++ @override+ Widget build(BuildContext context) {+ final l = AppLocalizations.of(context);+ final palette = SureColors.of(context).palette;+ final hideAmounts = context.watch<PrivacyProvider>().hidden;++ Widget body;+ if (_loading && _transactions.isEmpty) {+ body = const Center(child: CircularProgressIndicator());+ } else if (_failed && _transactions.isEmpty) {+ body = _centered(+ context,+ Icons.error_outline,+ l.budgetCategoryTransactionsLoadFailed,+ action: SureButton(+ label: l.commonTryAgain,+ onPressed: () => _loadPage(reset: true),+ variant: SureButtonVariant.outline,+ size: SureButtonSize.sm,+ ),+ );+ } else if (_transactions.isEmpty) {+ body = _centered(+ context,+ Icons.receipt_long_outlined,+ l.budgetCategoryTransactionsEmpty(widget.periodLabel),+ );+ } else {+ body = ListView.separated(+ physics: const AlwaysScrollableScrollPhysics(),+ itemCount: _transactions.length + (_hasMore || _failed ? 1 : 0),+ separatorBuilder: (_, __) =>+ Divider(height: 1, color: palette.borderSecondary),+ itemBuilder: (context, index) {+ if (index >= _transactions.length) {+ return Padding(+ padding: const EdgeInsets.all(SureSpacing.xl),+ child: Center(+ child: SureButton(+ label: _failed+ ? l.commonTryAgain+ : l.budgetCategoryTransactionsLoadMore,+ onPressed: _loading+ ? null+ : () => _loadPage(reset: _failed && _failedWasReset),+ loading: _loading,+ variant: SureButtonVariant.outline,+ size: SureButtonSize.sm,+ ),+ ),+ );+ }+ return _TransactionTile(+ transaction: _transactions[index],+ hideAmounts: hideAmounts,+ );+ },+ );+ }++ return Scaffold(+ appBar: AppBar(+ title: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(widget.title),+ Text(+ widget.periodLabel,+ style: Theme.of(context)+ .textTheme+ .bodySmall+ ?.copyWith(color: palette.textSecondary),+ ),+ ],+ ),+ ),+ body: RefreshIndicator(+ onRefresh: () => _loadPage(reset: true),+ child: body,+ ),+ );+ }++ Widget _centered(+ BuildContext context,+ IconData icon,+ String message, {+ Widget? action,+ }) {+ final palette = SureColors.of(context).palette;+ return ListView(+ physics: const AlwaysScrollableScrollPhysics(),+ padding: const EdgeInsets.all(SureSpacing.xxxl),+ children: [+ const SizedBox(height: SureSpacing.huge * 2),+ Icon(icon, size: 56, color: palette.textSubdued),+ const SizedBox(height: SureSpacing.xl),+ Text(+ message,+ textAlign: TextAlign.center,+ style: Theme.of(context)+ .textTheme+ .bodyMedium+ ?.copyWith(color: palette.textSecondary),+ ),+ if (action != null) ...[+ const SizedBox(height: SureSpacing.xl),+ Center(child: action),+ ],+ ],+ );+ }+}++class _TransactionTile extends StatelessWidget {+ const _TransactionTile({+ required this.transaction,+ required this.hideAmounts,+ });++ final Transaction transaction;+ final bool hideAmounts;++ Account? _account(BuildContext context) {+ try {+ final accounts = context.read<AccountsProvider>().accounts;+ for (final account in accounts) {+ if (account.id == transaction.accountId) return account;+ }+ } on ProviderNotFoundException {+ // Account names are optional context; the tile still renders.+ }+ return null;+ }++ @override+ Widget build(BuildContext context) {+ final palette = SureColors.of(context).palette;+ final textTheme = Theme.of(context).textTheme;+ final locale = Localizations.localeOf(context).toString();+ final isIncome = transaction.isIncome;+ final trend = isIncome ? MoneyTrend.inflow : MoneyTrend.outflow;+ final magnitude =+ transaction.amount.replaceFirst(RegExp('^[-\u2212+]'), '');+ final amount = '${isIncome ? '+' : '-'}$magnitude';++ final date = DateTime.tryParse(transaction.date);+ final subtitleParts = <String>[+ if (date != null) DateFormat.yMMMd(locale).format(date),+ if (_account(context)?.name case final String name) name,+ if (transaction.categoryName case final String category) category,+ ];++ return ListTile(+ contentPadding: const EdgeInsets.symmetric(+ horizontal: SureSpacing.xl,+ vertical: SureSpacing.xs,+ ),+ title: Text(+ transaction.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: textTheme.bodyLarge?.copyWith(+ fontWeight: SureTokens.weightMedium,+ ),+ ),+ subtitle: Text(+ subtitleParts.join(' · '),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: textTheme.bodySmall?.copyWith(color: palette.textSecondary),+ ),+ trailing: MoneyText(+ MoneyMasker.mask(amount, hidden: hideAmounts),+ trend: trend,+ style: textTheme.bodyLarge?.copyWith(+ fontWeight: SureTokens.weightMedium,+ ),+ ),+ );+ }+}diff --git a/mobile/lib/screens/budgets_screen.dart b/mobile/lib/screens/budgets_screen.dartnew file mode 100644index 0000000000..b97e46bc90--- /dev/null+++ b/mobile/lib/screens/budgets_screen.dart@@ -0,0 +1,493 @@+import 'package:flutter/material.dart';+import 'package:intl/intl.dart';+import 'package:provider/provider.dart';++import '../l10n/app_localizations.dart';+import '../models/budget.dart';+import '../providers/auth_provider.dart';+import '../providers/budgets_provider.dart';+import '../providers/privacy_provider.dart';+import '../services/connectivity_service.dart';+import '../theme/sure_colors.dart';+import '../theme/sure_spacing.dart';+import '../widgets/budget_category_row.dart';+import '../widgets/budget_summary_card.dart';+import '../widgets/sure_button.dart';+import '../widgets/sure_card.dart';+import '../widgets/sure_chip.dart';+import '../widgets/sure_segmented_control.dart';+import 'budget_category_transactions_screen.dart';++/// Monthly budget overview, matching the web Budgets page: month navigation,+/// budgeted / actual / remaining totals and a progress bar per category, with+/// subcategories nested under their parent. Tapping a category opens its+/// transactions for that budget period. Read-only: budgets are edited on web.+class BudgetsScreen extends StatefulWidget {+ const BudgetsScreen({super.key, this.provider, this.accessTokenLoader});++ /// Injected for tests; otherwise the screen owns its provider.+ final BudgetsProvider? provider;++ /// Injected for tests; defaults to [AuthProvider.getValidAccessToken].+ final Future<String?> Function()? accessTokenLoader;++ @override+ State<BudgetsScreen> createState() => _BudgetsScreenState();+}++enum _CategoryFilter { all, overBudget }++class _BudgetsScreenState extends State<BudgetsScreen> {+ late final BudgetsProvider _provider;+ late final bool _ownsProvider;+ _CategoryFilter _filter = _CategoryFilter.all;++ @override+ void initState() {+ super.initState();+ _ownsProvider = widget.provider == null;+ _provider = widget.provider ??+ BudgetsProvider(+ isOffline: () {+ if (!mounted) return false;+ try {+ return context.read<ConnectivityService>().isOffline;+ } on ProviderNotFoundException {+ return false;+ }+ },+ );+ WidgetsBinding.instance.addPostFrameCallback((_) => _load());+ }++ @override+ void dispose() {+ if (_ownsProvider) _provider.dispose();+ super.dispose();+ }++ Future<String?> _accessToken() {+ final loader = widget.accessTokenLoader;+ if (loader != null) return loader();+ return context.read<AuthProvider>().getValidAccessToken();+ }++ Future<void> _load({bool forceRefresh = false}) async {+ final token = await _accessToken();+ if (!mounted) return;+ if (token == null) {+ _provider.markUnauthorized();+ return;+ }+ await _provider.loadMonth(accessToken: token, forceRefresh: forceRefresh);+ }++ void _changeMonth(VoidCallback change) {+ change();+ setState(() => _filter = _CategoryFilter.all);+ _load();+ }++ Future<void> _selectBudget(String budgetId) async {+ final token = await _accessToken();+ if (!mounted) return;+ if (token == null) {+ _provider.markUnauthorized();+ return;+ }+ setState(() => _filter = _CategoryFilter.all);+ await _provider.selectBudget(accessToken: token, budgetId: budgetId);+ }++ void _openCategory(Budget budget, BudgetCategory bc, List<String> ids) {+ Navigator.push(+ context,+ MaterialPageRoute(+ builder: (_) => BudgetCategoryTransactionsScreen(+ title: bc.name,+ periodLabel: _periodLabel(context, budget.startDate, budget),+ categoryIds: ids,+ startDate: budget.startDate,+ endDate: budget.endDate,+ accessTokenLoader: widget.accessTokenLoader,+ ),+ ),+ );+ }++ static String _periodLabel(BuildContext context, DateTime month, Budget? b) {+ // The server name covers families with a custom month start+ // ("Oct 15 - Nov 14, 2026"); otherwise format the month locally.+ if (b != null && b.name.isNotEmpty) return b.name;+ final locale = Localizations.localeOf(context).toString();+ return DateFormat.yMMMM(locale).format(month);+ }++ @override+ Widget build(BuildContext context) {+ return ChangeNotifierProvider<BudgetsProvider>.value(+ value: _provider,+ child: Consumer<BudgetsProvider>(+ builder: (context, provider, _) => _buildScaffold(context, provider),+ ),+ );+ }++ Widget _buildScaffold(BuildContext context, BudgetsProvider provider) {+ final l = AppLocalizations.of(context);+ final hideAmounts = context.watch<PrivacyProvider>().hidden;++ return Scaffold(+ appBar: AppBar(title: Text(l.budgetsTitle)),+ body: RefreshIndicator(+ onRefresh: () => _load(forceRefresh: true),+ child: ListView(+ physics: const AlwaysScrollableScrollPhysics(),+ padding: const EdgeInsets.fromLTRB(+ SureSpacing.xl,+ SureSpacing.md,+ SureSpacing.xl,+ SureSpacing.huge,+ ),+ children: [+ _buildMonthHeader(context, provider),+ ..._buildBody(context, provider, hideAmounts),+ ],+ ),+ ),+ );+ }++ Widget _buildMonthHeader(BuildContext context, BudgetsProvider provider) {+ final l = AppLocalizations.of(context);+ final textTheme = Theme.of(context).textTheme;+ return Row(+ children: [+ IconButton(+ icon: const Icon(Icons.chevron_left),+ tooltip: l.budgetsPreviousMonth,+ onPressed: () => _changeMonth(provider.previousMonth),+ ),+ Expanded(+ child: Text(+ _periodLabel(context, provider.month, provider.budget),+ textAlign: TextAlign.center,+ style: textTheme.titleMedium,+ ),+ ),+ IconButton(+ icon: const Icon(Icons.chevron_right),+ tooltip: l.budgetsNextMonth,+ onPressed: provider.canGoNext+ ? () => _changeMonth(provider.nextMonth)+ : null,+ ),+ ],+ );+ }++ List<Widget> _buildBody(+ BuildContext context,+ BudgetsProvider provider,+ bool hideAmounts,+ ) {+ final l = AppLocalizations.of(context);+ final palette = SureColors.of(context).palette;++ if (provider.isLoading && !provider.hasLoadedMonth) {+ return const [+ Padding(+ padding: EdgeInsets.only(top: SureSpacing.huge * 3),+ child: Center(child: CircularProgressIndicator()),+ ),+ ];+ }++ // A failed refresh keeps the month already loaded on screen (with a+ // banner), like the offline path; only a month never loaded gets the+ // full-screen error.+ switch (provider.refreshFailed ? null : provider.error) {+ case BudgetsLoadError.offline:+ return [+ _message(+ context,+ icon: Icons.cloud_off_outlined,+ title: l.budgetsOfflineTitle,+ body: l.budgetsOfflineMessage,+ onRetry: () => _load(forceRefresh: true),+ ),+ ];+ case BudgetsLoadError.unauthorized:+ return [+ _message(+ context,+ icon: Icons.lock_outline,+ title: l.budgetsLoadFailed,+ body: l.budgetsSessionExpired,+ ),+ ];+ case BudgetsLoadError.failed:+ return [+ _message(+ context,+ icon: Icons.error_outline,+ title: l.budgetsLoadFailed,+ body: null,+ onRetry: () => _load(forceRefresh: true),+ ),+ ];+ case null:+ break;+ }++ if (!provider.hasLoadedMonth) return const [];++ final budget = provider.budget;+ if (budget == null) {+ final locale = Localizations.localeOf(context).toString();+ return [+ _message(+ context,+ icon: Icons.pie_chart_outline,+ title: l.budgetsNoBudgetTitle(+ DateFormat.yMMMM(locale).format(provider.month),+ ),+ body: l.budgetsNoBudgetMessage,+ ),+ ];+ }++ final widgets = <Widget>[];++ if (provider.showingCachedWhileOffline) {+ widgets.add(+ Padding(+ padding: const EdgeInsets.only(bottom: SureSpacing.lg),+ child: Row(+ children: [+ Icon(Icons.cloud_off_outlined,+ size: 16, color: palette.textSecondary),+ const SizedBox(width: SureSpacing.sm),+ Expanded(+ child: Text(+ l.budgetsOfflineCached,+ style: Theme.of(context)+ .textTheme+ .bodySmall+ ?.copyWith(color: palette.textSecondary),+ ),+ ),+ ],+ ),+ ),+ );+ }++ if (provider.refreshFailed) {+ widgets.add(+ Padding(+ padding: const EdgeInsets.only(bottom: SureSpacing.lg),+ child: Row(+ children: [+ Icon(Icons.error_outline, size: 16, color: palette.textSecondary),+ const SizedBox(width: SureSpacing.sm),+ Expanded(+ child: Text(+ l.budgetsRefreshFailed,+ style: Theme.of(context)+ .textTheme+ .bodySmall+ ?.copyWith(color: palette.textSecondary),+ ),+ ),+ TextButton(+ onPressed: () => _load(forceRefresh: true),+ child: Text(l.commonTryAgain),+ ),+ ],+ ),+ ),+ );+ }++ if (provider.monthBudgets.length > 1) {+ widgets.add(+ Padding(+ padding: const EdgeInsets.only(bottom: SureSpacing.lg),+ child: Wrap(+ spacing: SureSpacing.md,+ runSpacing: SureSpacing.md,+ children: [+ for (var i = 0; i < provider.monthBudgets.length; i++)+ SureChip(+ label: l.budgetsBudgetNumber(i + 1),+ selected: provider.monthBudgets[i].id == budget.id,+ onSelected: (_) => _selectBudget(provider.monthBudgets[i].id),+ ),+ ],+ ),+ ),+ );+ }++ if (provider.isLoading) {+ widgets.add(const LinearProgressIndicator(minHeight: 2));+ widgets.add(const SizedBox(height: SureSpacing.md));+ }++ widgets.add(BudgetSummaryCard(budget: budget, hideAmounts: hideAmounts));++ if (!budget.initialized) {+ widgets.add(const SizedBox(height: SureSpacing.lg));+ widgets.add(+ _message(+ context,+ icon: Icons.tune,+ title: null,+ body: l.budgetsNotSetUpMessage,+ ),+ );+ }++ widgets.addAll(_buildCategories(context, provider, budget, hideAmounts));+ return widgets;+ }++ List<Widget> _buildCategories(+ BuildContext context,+ BudgetsProvider provider,+ Budget budget,+ bool hideAmounts,+ ) {+ final l = AppLocalizations.of(context);+ final palette = SureColors.of(context).palette;+ final groups = provider.visibleGroups;+ final overCount = provider.overBudgetCount;+ final filter = overCount == 0 ? _CategoryFilter.all : _filter;++ final rows = <Widget>[];+ void addRow(BudgetCategory bc, List<String> ids, {bool indented = false}) {+ if (rows.isNotEmpty) {+ rows.add(Divider(height: 1, color: palette.borderSecondary));+ }+ rows.add(+ BudgetCategoryRow(+ key: ValueKey('budget-category-${bc.id}'),+ budgetCategory: bc,+ hideAmounts: hideAmounts,+ indented: indented,+ onTap: () => _openCategory(budget, bc, ids),+ ),+ );+ }++ for (final group in groups) {+ // Like the web, a parent that isn't itself visible only exists as the+ // container of its visible subcategories: no row, no indent.+ final showParent = provider.showsAllCategories || group.parent.isVisible;+ if (filter == _CategoryFilter.overBudget) {+ if (group.parent.isOverBudget) {+ addRow(group.parent, group.categoryIds);+ }+ for (final child in group.children.where((c) => c.isOverBudget)) {+ addRow(+ child,+ [child.category.id],+ indented: group.parent.isOverBudget,+ );+ }+ } else {+ if (showParent) addRow(group.parent, group.categoryIds);+ for (final child in group.children) {+ addRow(child, [child.category.id], indented: showParent);+ }+ }+ }++ return [+ const SizedBox(height: SureSpacing.xxxl),+ Padding(+ padding: const EdgeInsets.only(bottom: SureSpacing.md),+ child: Text(+ l.budgetsCategoriesTitle,+ style: Theme.of(context).textTheme.titleMedium,+ ),+ ),+ if (overCount > 0)+ Padding(+ padding: const EdgeInsets.only(bottom: SureSpacing.lg),+ child: SureSegmentedControl<_CategoryFilter>(+ segments: [+ SureSegment(value: _CategoryFilter.all, label: l.commonAll),+ SureSegment(+ value: _CategoryFilter.overBudget,+ label: l.budgetsFilterOverBudget(overCount),+ ),+ ],+ selected: filter,+ onChanged: (value) => setState(() => _filter = value),+ ),+ ),+ if (rows.isEmpty)+ _message(+ context,+ icon: Icons.category_outlined,+ title: null,+ body: l.budgetsNoCategories,+ )+ else+ SureCard(+ padding: EdgeInsets.zero,+ child: Column(children: rows),+ ),+ ];+ }++ Widget _message(+ BuildContext context, {+ required IconData icon,+ required String? title,+ String? body,+ VoidCallback? onRetry,+ }) {+ final l = AppLocalizations.of(context);+ final palette = SureColors.of(context).palette;+ final textTheme = Theme.of(context).textTheme;+ return Padding(+ padding: EdgeInsets.only(+ top: title == null ? 0 : SureSpacing.huge * 2,+ ),+ child: Column(+ children: [+ Icon(icon, size: title == null ? 32 : 56, color: palette.textSubdued),+ if (title != null) ...[+ const SizedBox(height: SureSpacing.xl),+ Text(+ title,+ textAlign: TextAlign.center,+ style: textTheme.titleMedium,+ ),+ ],+ if (body != null && body.isNotEmpty) ...[+ const SizedBox(height: SureSpacing.md),+ Text(+ body,+ textAlign: TextAlign.center,+ style:+ textTheme.bodyMedium?.copyWith(color: palette.textSecondary),+ ),+ ],+ if (onRetry != null) ...[+ const SizedBox(height: SureSpacing.xl),+ SureButton(+ label: l.commonTryAgain,+ onPressed: onRetry,+ variant: SureButtonVariant.outline,+ size: SureButtonSize.sm,+ ),+ ],+ ],+ ),+ );+ }+}diff --git a/mobile/lib/screens/more_screen.dart b/mobile/lib/screens/more_screen.dartindex ae4e594d58..60b89d656b 100644--- a/mobile/lib/screens/more_screen.dart+++ b/mobile/lib/screens/more_screen.dart@@ -3,6 +3,7 @@ import '../l10n/app_localizations.dart';import '../theme/sure_colors.dart';import '../theme/sure_tokens.dart';import '../widgets/sure_list_group.dart';+import 'budgets_screen.dart';import 'calendar_screen.dart';import 'recent_transactions_screen.dart';@@ -22,6 +23,20 @@ class MoreScreen extends StatelessWidget {children: [SureListGroup(children: [+ SureListRow(+ leading: _iconBadge(context, Icons.pie_chart_outline),+ title: l.moreBudgets,+ subtitle: l.moreBudgetsSubtitle,+ showChevron: true,+ onTap: () {+ Navigator.push(+ context,+ MaterialPageRoute(+ builder: (context) => const BudgetsScreen(),+ ),+ );+ },+ ),SureListRow(leading: _iconBadge(context, Icons.calendar_month),title: l.moreCalendar,diff --git a/mobile/lib/services/budgets_service.dart b/mobile/lib/services/budgets_service.dartnew file mode 100644index 0000000000..ce665e56b5--- /dev/null+++ b/mobile/lib/services/budgets_service.dart@@ -0,0 +1,186 @@+import 'dart:convert';++import 'package:http/http.dart' as http;++import '../models/budget.dart';+import 'api_config.dart';+import 'response_list_parser.dart';++/// Read-only client for the budgets API (`/api/v1/budgets` and+/// `/api/v1/budget_categories`).+///+/// Results use the same `{'success': bool, ...}` map shape as the other+/// services so providers can treat them uniformly, with `'unauthorized'` as+/// the error for a 401.+class BudgetsService {+ BudgetsService({http.Client? client}) : _client = client ?? http.Client();++ final http.Client _client;++ static const Duration _timeout = Duration(seconds: 30);++ /// Lists budgets, optionally within a date window. The index endpoint does+ /// not include actual/available amounts; use [getBudget] for those.+ Future<Map<String, dynamic>> getBudgets({+ required String accessToken,+ DateTime? startDate,+ DateTime? endDate,+ int? page,+ int? perPage,+ }) async {+ final query = <String, String>{+ if (startDate != null) 'start_date': formatApiDate(startDate),+ if (endDate != null) 'end_date': formatApiDate(endDate),+ if (page != null) 'page': page.toString(),+ if (perPage != null) 'per_page': perPage.toString(),+ };++ final result = await _get(+ accessToken,+ '/api/v1/budgets',+ query,+ 'Failed to load budgets',+ );+ if (result['success'] != true) return result;++ final budgets = extractJsonObjectList(result['data'], key: 'budgets')+ .map(Budget.fromJson)+ .where((b) => b.id.isNotEmpty)+ .toList();+ return {+ 'success': true,+ 'budgets': budgets,+ 'pagination': _pagination(result['data']),+ };+ }++ /// Fetches one budget including its derived amounts.+ Future<Map<String, dynamic>> getBudget({+ required String accessToken,+ required String id,+ }) async {+ final result = await _get(+ accessToken,+ '/api/v1/budgets/${Uri.encodeComponent(id)}',+ const {},+ 'Failed to load budget',+ );+ if (result['success'] != true) return result;++ final data = result['data'];+ if (data is! Map) {+ return {'success': false, 'error': 'Failed to load budget'};+ }+ return {+ 'success': true,+ 'budget': Budget.fromJson(data.cast<String, dynamic>()),+ };+ }++ /// Lists the category lines of a budget. Like the budgets index, this omits+ /// actual spending; use [getBudgetCategory] for those.+ Future<Map<String, dynamic>> getBudgetCategories({+ required String accessToken,+ String? budgetId,+ int? page,+ int? perPage,+ }) async {+ final query = <String, String>{+ if (budgetId != null) 'budget_id': budgetId,+ if (page != null) 'page': page.toString(),+ if (perPage != null) 'per_page': perPage.toString(),+ };++ final result = await _get(+ accessToken,+ '/api/v1/budget_categories',+ query,+ 'Failed to load budget categories',+ );+ if (result['success'] != true) return result;++ final categories =+ extractJsonObjectList(result['data'], key: 'budget_categories')+ .map(BudgetCategory.fromJson)+ .where((c) => c.id.isNotEmpty)+ .toList();+ return {+ 'success': true,+ 'budget_categories': categories,+ 'pagination': _pagination(result['data']),+ };+ }++ /// Fetches one budget category including actual spending and what is left.+ Future<Map<String, dynamic>> getBudgetCategory({+ required String accessToken,+ required String id,+ }) async {+ final result = await _get(+ accessToken,+ '/api/v1/budget_categories/${Uri.encodeComponent(id)}',+ const {},+ 'Failed to load budget category',+ );+ if (result['success'] != true) return result;++ final data = result['data'];+ if (data is! Map) {+ return {'success': false, 'error': 'Failed to load budget category'};+ }+ return {+ 'success': true,+ 'budget_category': BudgetCategory.fromJson(data.cast<String, dynamic>()),+ };+ }++ Future<Map<String, dynamic>> _get(+ String accessToken,+ String path,+ Map<String, String> query,+ String failureMessage,+ ) async {+ final baseUri = Uri.parse('${ApiConfig.baseUrl}$path');+ final url =+ query.isEmpty ? baseUri : baseUri.replace(queryParameters: query);++ try {+ final response = await _client.get(+ url,+ headers: {+ ...ApiConfig.getAuthHeaders(accessToken),+ 'Content-Type': 'application/json',+ },+ ).timeout(_timeout);++ if (response.statusCode == 200) {+ return {'success': true, 'data': jsonDecode(response.body)};+ } else if (response.statusCode == 401) {+ return {'success': false, 'error': 'unauthorized'};+ } else if (response.statusCode == 404) {+ return {'success': false, 'error': 'not_found'};+ }+ return {+ 'success': false,+ 'error': extractErrorMessage(response.body, fallback: failureMessage),+ };+ } catch (e) {+ return {'success': false, 'error': 'Network error: ${e.toString()}'};+ }+ }++ static Map<String, dynamic>? _pagination(dynamic data) {+ if (data is Map && data['pagination'] is Map) {+ return (data['pagination'] as Map).cast<String, dynamic>();+ }+ return null;+ }++ /// `YYYY-MM-DD`, the format the API date filters expect.+ static String formatApiDate(DateTime date) {+ final y = date.year.toString().padLeft(4, '0');+ final m = date.month.toString().padLeft(2, '0');+ final d = date.day.toString().padLeft(2, '0');+ return '$y-$m-$d';+ }+}diff --git a/mobile/lib/services/transactions_service.dart b/mobile/lib/services/transactions_service.dartindex 38bd912797..da6c8f2e17 100644--- a/mobile/lib/services/transactions_service.dart+++ b/mobile/lib/services/transactions_service.dart@@ -95,8 +95,12 @@ class TransactionsService {String? accountId,int? page,int? perPage,+ String? startDate,+ String? endDate,+ List<String>? categoryIds,}) async {- final Map<String, String> queryParams = {};+ // Values are a String or, for repeated Rails array params, a List<String>.+ final Map<String, dynamic> queryParams = {};if (accountId != null) {queryParams['account_id'] = accountId;@@ -107,6 +111,15 @@ class TransactionsService {if (perPage != null) {queryParams['per_page'] = perPage.toString();}+ if (startDate != null) {+ queryParams['start_date'] = startDate;+ }+ if (endDate != null) {+ queryParams['end_date'] = endDate;+ }+ if (categoryIds != null && categoryIds.isNotEmpty) {+ queryParams['category_ids[]'] = categoryIds;+ }final baseUri = Uri.parse('${ApiConfig.baseUrl}/api/v1/transactions');final url = queryParams.isNotEmptydiff --git a/mobile/lib/widgets/budget_category_row.dart b/mobile/lib/widgets/budget_category_row.dartnew file mode 100644index 0000000000..a3d5b188d7--- /dev/null+++ b/mobile/lib/widgets/budget_category_row.dart@@ -0,0 +1,247 @@+import 'package:flutter/material.dart';++import '../l10n/app_localizations.dart';+import '../models/budget.dart';+import '../theme/sure_colors.dart';+import '../theme/sure_spacing.dart';+import '../theme/sure_tokens.dart';+import '../utils/money_masker.dart';+import 'budget_progress_bar.dart';+import 'money_text.dart';++/// One budget category line: name, spent-of-budget progress bar and what is+/// left (or how far over). Subcategories render indented under their parent.+class BudgetCategoryRow extends StatelessWidget {+ const BudgetCategoryRow({+ super.key,+ required this.budgetCategory,+ required this.hideAmounts,+ this.onTap,+ this.indented = false,+ });++ final BudgetCategory budgetCategory;+ final bool hideAmounts;+ final VoidCallback? onTap;+ final bool indented;++ String _money(String? formatted) =>+ MoneyMasker.mask(formatted ?? '--', hidden: hideAmounts);++ /// The API formats an overspend as a negative amount; show its magnitude.+ static String _abs(String formatted) =>+ formatted.replaceFirst(RegExp('^[-\u2212]'), '');++ @override+ Widget build(BuildContext context) {+ final l = AppLocalizations.of(context);+ final palette = SureColors.of(context).palette;+ final textTheme = Theme.of(context).textTheme;+ final bc = budgetCategory;+ final color = parseCategoryColor(bc.category.color) ?? palette.textSubdued;+ final over = bc.hasDerivedAmounts && bc.isOverBudget;+ final near = bc.hasDerivedAmounts && bc.isNearLimit;++ final String trailing;+ Color trailingColor = palette.textSecondary;+ if (!bc.hasDerivedAmounts) {+ trailing = '';+ } else if (bc.inheritsParentBudget) {+ trailing = l.budgetsSharedBudget;+ if (over) trailingColor = palette.destructive;+ } else if (!bc.isBudgeted) {+ trailing = l.budgetsNoLimit;+ if (over) trailingColor = palette.destructive;+ } else if (over) {+ trailing = l.budgetsOverBy(_money(_abs(bc.availableToSpend ?? '')));+ trailingColor = palette.destructive;+ } else {+ trailing = l.budgetsAmountLeft(_money(bc.availableToSpend));+ }++ final spentLine = bc.hasDerivedAmounts+ ? (bc.isBudgeted && !bc.inheritsParentBudget+ ? '${_money(bc.actualSpending)} '+ '${l.budgetsOfAmount(_money(bc.displayBudgetedSpending))}'+ : _money(bc.actualSpending))+ : l.budgetsOfAmount(_money(bc.displayBudgetedSpending));++ return InkWell(+ onTap: onTap,+ child: Padding(+ padding: EdgeInsetsDirectional.fromSTEB(+ indented ? SureSpacing.xl + SureSpacing.huge : SureSpacing.xl,+ SureSpacing.lg,+ SureSpacing.xl,+ SureSpacing.lg,+ ),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ _CategoryAvatar(+ name: bc.name,+ color: color,+ size: indented ? 28 : 36,+ ),+ const SizedBox(width: SureSpacing.lg),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ children: [+ Expanded(+ child: Text(+ bc.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: textTheme.bodyLarge?.copyWith(+ fontWeight: SureTokens.weightMedium,+ color: palette.textPrimary,+ ),+ ),+ ),+ if (over)+ _Badge(+ label: l.budgetsOverBudget,+ color: palette.destructive,+ )+ else if (near)+ _Badge(+ label: l.budgetsNearLimit,+ color: palette.warning,+ ),+ ],+ ),+ const SizedBox(height: SureSpacing.sm),+ BudgetProgressBar(+ fraction: bc.spentFraction,+ color: color,+ overBudget: over,+ nearLimit: near,+ hidden: hideAmounts,+ ),+ const SizedBox(height: SureSpacing.sm),+ Row(+ children: [+ Expanded(+ child: Text(+ spentLine,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: SureMoney.tabular(+ textTheme.bodySmall?.copyWith(+ color: palette.textSecondary,+ ),+ ),+ ),+ ),+ if (trailing.isNotEmpty) ...[+ const SizedBox(width: SureSpacing.md),+ Expanded(+ child: Text(+ trailing,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ textAlign: TextAlign.end,+ style: SureMoney.tabular(+ textTheme.bodySmall?.copyWith(+ color: trailingColor,+ fontWeight:+ over ? SureTokens.weightMedium : null,+ ),+ ),+ ),+ ),+ ],+ ],+ ),+ if (bc.hasDerivedAmounts &&+ !bc.inheritsParentBudget &&+ (bc.rolledOverAmountCents ?? 0) > 0) ...[+ const SizedBox(height: SureSpacing.xs),+ Text(+ l.budgetsRolledOver(_money(bc.rolledOverAmount)),+ style: SureMoney.tabular(+ textTheme.bodySmall?.copyWith(+ color: palette.textSubdued,+ ),+ ),+ ),+ ],+ ],+ ),+ ),+ ],+ ),+ ),+ );+ }+}++class _CategoryAvatar extends StatelessWidget {+ const _CategoryAvatar({+ required this.name,+ required this.color,+ required this.size,+ });++ final String name;+ final Color color;+ final double size;++ @override+ Widget build(BuildContext context) {+ // First user-perceived character, so a name starting with an emoji (a+ // surrogate pair or a ZWJ sequence) isn't cut in half.+ final trimmed = name.trim();+ final initial =+ trimmed.isEmpty ? '?' : trimmed.characters.first.toUpperCase();+ return Container(+ width: size,+ height: size,+ alignment: Alignment.center,+ decoration: BoxDecoration(+ color: color.withValues(alpha: 0.12),+ shape: BoxShape.circle,+ ),+ child: Text(+ initial,+ style: TextStyle(+ color: color,+ fontWeight: SureTokens.weightSemibold,+ fontSize: size * 0.42,+ ),+ ),+ );+ }+}++class _Badge extends StatelessWidget {+ const _Badge({required this.label, required this.color});++ final String label;+ final Color color;++ @override+ Widget build(BuildContext context) {+ return Container(+ margin: const EdgeInsetsDirectional.only(start: SureSpacing.md),+ padding: const EdgeInsets.symmetric(+ horizontal: SureSpacing.sm,+ vertical: 2,+ ),+ decoration: BoxDecoration(+ color: color.withValues(alpha: 0.1),+ borderRadius: BorderRadius.circular(SureTokens.radiusMd),+ ),+ child: Text(+ label,+ style: Theme.of(context).textTheme.labelSmall?.copyWith(+ color: color,+ fontWeight: SureTokens.weightMedium,+ ),+ ),+ );+ }+}diff --git a/mobile/lib/widgets/budget_progress_bar.dart b/mobile/lib/widgets/budget_progress_bar.dartnew file mode 100644index 0000000000..c88ea6f1f3--- /dev/null+++ b/mobile/lib/widgets/budget_progress_bar.dart@@ -0,0 +1,76 @@+import 'package:flutter/material.dart';++import '../theme/sure_colors.dart';++/// Thin horizontal bar showing how much of a budget is spent.+///+/// [fraction] is spent / available (1.0 == 100%). The fill is capped at full+/// width; colour follows the web budget card: the category colour while on+/// track, `warning` when near the limit and `destructive` once over.+///+/// With [hidden] (privacy mode) only the empty track is drawn and the+/// percentage is left out of the semantics, since the share spent gives the+/// masked amounts away.+class BudgetProgressBar extends StatelessWidget {+ const BudgetProgressBar({+ super.key,+ required this.fraction,+ this.color,+ this.overBudget = false,+ this.nearLimit = false,+ this.hidden = false,+ this.height = 6,+ });++ final double fraction;+ final Color? color;+ final bool overBudget;+ final bool nearLimit;+ final bool hidden;+ final double height;++ @override+ Widget build(BuildContext context) {+ final palette = SureColors.of(context).palette;+ final fill = overBudget+ ? palette.destructive+ : nearLimit+ ? palette.warning+ : (color ?? palette.success);+ final clamped = hidden || fraction.isNaN ? 0.0 : fraction.clamp(0.0, 1.0);++ return Semantics(+ value: hidden ? null : '${(clamped * 100).round()}%',+ child: ClipRRect(+ borderRadius: BorderRadius.circular(height),+ child: SizedBox(+ height: height,+ child: Stack(+ fit: StackFit.expand,+ children: [+ ColoredBox(color: palette.surfaceInset),+ FractionallySizedBox(+ alignment: AlignmentDirectional.centerStart,+ widthFactor: clamped,+ child: ColoredBox(color: fill),+ ),+ ],+ ),+ ),+ ),+ );+ }+}++/// Parses a category colour as sent by the API (`#RRGGBB`), or null.+Color? parseCategoryColor(String? hex) {+ if (hex == null) return null;+ var value = hex.trim();+ if (value.startsWith('#')) value = value.substring(1);+ if (value.length == 3) {+ value = value.split('').map((c) => '$c$c').join();+ }+ if (value.length != 6) return null;+ final parsed = int.tryParse(value, radix: 16);+ return parsed == null ? null : Color(0xFF000000 | parsed);+}diff --git a/mobile/lib/widgets/budget_summary_card.dart b/mobile/lib/widgets/budget_summary_card.dartnew file mode 100644index 0000000000..cbdd83e620--- /dev/null+++ b/mobile/lib/widgets/budget_summary_card.dart@@ -0,0 +1,168 @@+import 'package:flutter/material.dart';++import '../l10n/app_localizations.dart';+import '../models/budget.dart';+import '../theme/sure_colors.dart';+import '../theme/sure_spacing.dart';+import '../theme/sure_tokens.dart';+import '../utils/money_masker.dart';+import 'budget_progress_bar.dart';+import 'money_text.dart';+import 'sure_card.dart';++/// Month totals for a budget: budgeted, actual and remaining spending with an+/// overall progress bar, plus actual vs. expected income.+class BudgetSummaryCard extends StatelessWidget {+ const BudgetSummaryCard({+ super.key,+ required this.budget,+ required this.hideAmounts,+ });++ final Budget budget;+ final bool hideAmounts;++ String _money(String? formatted) =>+ MoneyMasker.mask(formatted ?? '--', hidden: hideAmounts);++ @override+ Widget build(BuildContext context) {+ final l = AppLocalizations.of(context);+ final palette = SureColors.of(context).palette;+ final textTheme = Theme.of(context).textTheme;+ final over = budget.isOverBudget;++ return SureCard(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Expanded(+ child: _Stat(+ label: l.budgetsBudgeted,+ value: _money(budget.budgetedSpending),+ ),+ ),+ Expanded(+ child: _Stat(+ label: l.budgetsActual,+ value: _money(budget.actualSpending),+ ),+ ),+ Expanded(+ child: _Stat(+ label: l.budgetsRemaining,+ value: _money(budget.availableToSpend),+ valueColor: over ? palette.destructive : null,+ alignEnd: true,+ ),+ ),+ ],+ ),+ if (budget.initialized) ...[+ const SizedBox(height: SureSpacing.lg),+ BudgetProgressBar(+ fraction: budget.spentFraction,+ overBudget: over,+ nearLimit: budget.isNearLimit,+ hidden: hideAmounts,+ height: 8,+ ),+ ],+ const SizedBox(height: SureSpacing.lg),+ Divider(height: 1, color: palette.borderSecondary),+ const SizedBox(height: SureSpacing.lg),+ Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ l.budgetsIncome,+ style: textTheme.bodyMedium?.copyWith(+ color: palette.textSecondary,+ ),+ ),+ const SizedBox(width: SureSpacing.lg),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.end,+ children: [+ MoneyText(+ _money(budget.actualIncome),+ trend: MoneyTrend.inflow,+ textAlign: TextAlign.end,+ overflow: TextOverflow.ellipsis,+ style: textTheme.bodyMedium?.copyWith(+ fontWeight: SureTokens.weightMedium,+ ),+ ),+ if (budget.expectedIncome != null)+ Text(+ l.budgetsExpectedIncome(_money(budget.expectedIncome)),+ textAlign: TextAlign.end,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: SureMoney.tabular(+ textTheme.bodySmall?.copyWith(+ color: palette.textSubdued,+ ),+ ),+ ),+ ],+ ),+ ),+ ],+ ),+ ],+ ),+ );+ }+}++class _Stat extends StatelessWidget {+ const _Stat({+ required this.label,+ required this.value,+ this.valueColor,+ this.alignEnd = false,+ });++ final String label;+ final String value;+ final Color? valueColor;+ final bool alignEnd;++ @override+ Widget build(BuildContext context) {+ final palette = SureColors.of(context).palette;+ final textTheme = Theme.of(context).textTheme;+ return Column(+ crossAxisAlignment:+ alignEnd ? CrossAxisAlignment.end : CrossAxisAlignment.start,+ children: [+ Text(+ label,+ style: textTheme.bodySmall?.copyWith(color: palette.textSecondary),+ ),+ const SizedBox(height: SureSpacing.xs),+ FittedBox(+ fit: BoxFit.scaleDown,+ alignment: alignEnd+ ? AlignmentDirectional.centerEnd+ : AlignmentDirectional.centerStart,+ child: Text(+ value,+ maxLines: 1,+ style: SureMoney.tabular(+ textTheme.titleMedium?.copyWith(+ fontWeight: SureTokens.weightSemibold,+ color: valueColor ?? palette.textPrimary,+ ),+ ),+ ),+ ),+ ],+ );+ }+}diff --git a/mobile/test/models/budget_test.dart b/mobile/test/models/budget_test.dartnew file mode 100644index 0000000000..27ee082211--- /dev/null+++ b/mobile/test/models/budget_test.dart@@ -0,0 +1,241 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:sure_mobile/models/budget.dart';++import '../support/budget_fixtures.dart';++void main() {+ group('Budget', () {+ test('parses show payload with derived amounts', () {+ final budget = Budget.fromJson(budgetJson());++ expect(budget.id, 'budget_oct');+ expect(budget.startDate, DateTime(2026, 10, 1));+ expect(budget.name, 'October 2026');+ expect(budget.budgetedSpending, r'$2,000.00');+ expect(budget.actualSpendingCents, 150000);+ expect(budget.availableToSpend, r'$500.00');+ expect(budget.hasDerivedAmounts, isTrue);+ expect(budget.isOverBudget, isFalse);+ expect(budget.spentFraction, closeTo(0.75, 0.0001));+ });++ test('isNearLimit uses the same 90% rule as category lines', () {+ Budget budget(int actual, int available) => Budget.fromJson(+ budgetJson(actualCents: actual, availableCents: available),+ );+ expect(budget(180000, 20000).isNearLimit, isTrue); // 90%+ expect(budget(170000, 30000).isNearLimit, isFalse); // 85%+ expect(budget(210000, -10000).isNearLimit, isFalse); // over, not near+ });++ test('index payload has no derived amounts', () {+ final json = budgetJson()..remove('actual_spending_cents');+ expect(Budget.fromJson(json).hasDerivedAmounts, isFalse);+ });++ test('uninitialized budget has null budgeted spending', () {+ final budget = Budget.fromJson(budgetJson(initialized: false));+ expect(budget.initialized, isFalse);+ expect(budget.budgetedSpending, isNull);+ });++ test('negative remaining is over budget', () {+ final budget = Budget.fromJson(+ budgetJson(actualCents: 250000, availableCents: -50000),+ );+ expect(budget.isOverBudget, isTrue);+ expect(budget.spentFraction, closeTo(1.25, 0.0001));+ });+ });++ group('BudgetCategory', () {+ BudgetCategory find(String id) => BudgetCategory.fromJson(+ octoberCategories().firstWhere((c) => c['id'] == id),+ );++ test('on track category near its limit', () {+ final food = find('bc_food');+ expect(food.isBudgeted, isTrue);+ expect(food.isOverBudget, isFalse);+ expect(food.spentFraction, closeTo(0.95, 0.0001));+ expect(food.isNearLimit, isTrue);+ expect(food.isVisible, isTrue);+ });++ test('subcategory with its own limit can be over budget', () {+ final groceries = find('bc_groceries');+ expect(groceries.subcategory, isTrue);+ expect(groceries.parentCategoryId, 'cat_food');+ expect(groceries.isOverBudget, isTrue);+ expect(groceries.isNearLimit, isFalse);+ expect(groceries.spentFraction, closeTo(1.3, 0.0001));+ });++ test('shared subcategory measures against the parent allocation', () {+ final restaurants = find('bc_restaurants');+ expect(restaurants.inheritsParentBudget, isTrue);+ expect(restaurants.isOverBudget, isFalse);+ expect(restaurants.spentFraction, closeTo(0.3, 0.0001));+ });++ test('rollover counts toward what there is to spend', () {+ final transport = find('bc_transport');+ expect(transport.effectiveBudgetCents, 35000);+ expect(transport.spentFraction, closeTo(12000 / 35000, 0.0001));+ });++ test('unbudgeted without spending is hidden, with spending is over', () {+ expect(find('bc_gifts').isVisible, isFalse);+ expect(find('bc_gifts').isOverBudget, isFalse);++ final spent = BudgetCategory.fromJson(+ budgetCategoryJson(+ id: 'bc_misc',+ categoryId: 'cat_misc',+ name: 'Misc',+ actualCents: 1000,+ ),+ );+ expect(spent.isVisible, isTrue);+ expect(spent.isOverBudget, isTrue);+ });++ test('shared subcategory without spending is hidden', () {+ final idle = BudgetCategory.fromJson(+ budgetCategoryJson(+ id: 'bc_idle',+ categoryId: 'cat_idle',+ name: 'Idle',+ parentId: 'cat_food',+ inheritsParent: true,+ displayBudgetedCents: 80000,+ availableCents: 0,+ ),+ );+ expect(idle.isVisible, isFalse);+ });+ });++ group('BudgetCategoryGroup.build', () {+ test('nests subcategories under their parent in server order', () {+ final groups = BudgetCategoryGroup.build(+ octoberCategories().map(BudgetCategory.fromJson).toList(),+ );++ expect(groups.map((g) => g.parent.name), ['Food', 'Gifts', 'Transport']);+ expect(+ groups.first.children.map((c) => c.name),+ ['Groceries', 'Restaurants'],+ );+ expect(+ groups.first.categoryIds,+ ['cat_food', 'cat_groceries', 'cat_restaurants'],+ );+ expect(groups.first.hasOverBudget, isTrue);+ });++ test('shared subcategory excludes ring-fenced sibling allocations', () {+ final groups = BudgetCategoryGroup.build(+ octoberCategories().map(BudgetCategory.fromJson).toList(),+ );+ final restaurants =+ groups.first.children.firstWhere((c) => c.name == 'Restaurants');++ // $800 Food less $400 ring-fenced for Groceries leaves a $400 pool;+ // $240 spent is 60% of it (web: percent_of_budget_spent).+ expect(restaurants.sharedBudgetCents, 40000);+ expect(restaurants.spentFraction, closeTo(0.6, 0.0001));+ // Ring-fenced siblings are unchanged.+ final groceries =+ groups.first.children.firstWhere((c) => c.name == 'Groceries');+ expect(groceries.sharedBudgetCents, isNull);+ expect(groceries.spentFraction, closeTo(1.3, 0.0001));+ });++ test('shared pool ignores ring-fenced siblings\' rollover', () {+ // The API's parent rollover is display_rolled_over_amount: its own $0+ // plus the ring-fenced child's $50. Rails' pool is 1000 - 200 = 800.+ final groups = BudgetCategoryGroup.build([+ BudgetCategory.fromJson(budgetCategoryJson(+ id: 'bc_p',+ categoryId: 'cat_p',+ name: 'Parent',+ budgetedCents: 100000,+ rolledOverCents: 5000,+ )),+ BudgetCategory.fromJson(budgetCategoryJson(+ id: 'bc_rf',+ categoryId: 'cat_rf',+ name: 'Ring-fenced',+ parentId: 'cat_p',+ budgetedCents: 20000,+ rolledOverCents: 5000,+ )),+ BudgetCategory.fromJson(budgetCategoryJson(+ id: 'bc_sh',+ categoryId: 'cat_sh',+ name: 'Shared',+ parentId: 'cat_p',+ inheritsParent: true,+ displayBudgetedCents: 100000,+ actualCents: 1000,+ )),+ ]);+ expect(groups.single.children.last.sharedBudgetCents, 80000);+ });++ test('shared pool never goes below zero', () {+ final groups = BudgetCategoryGroup.build([+ BudgetCategory.fromJson(budgetCategoryJson(+ id: 'bc_p',+ categoryId: 'cat_p',+ name: 'Parent',+ budgetedCents: 10000,+ )),+ BudgetCategory.fromJson(budgetCategoryJson(+ id: 'bc_rf',+ categoryId: 'cat_rf',+ name: 'Ring-fenced',+ parentId: 'cat_p',+ budgetedCents: 15000,+ )),+ BudgetCategory.fromJson(budgetCategoryJson(+ id: 'bc_sh',+ categoryId: 'cat_sh',+ name: 'Shared',+ parentId: 'cat_p',+ inheritsParent: true,+ displayBudgetedCents: 10000,+ actualCents: 500,+ availableCents: 0,+ )),+ ]);+ final shared = groups.single.children.last;+ expect(shared.sharedBudgetCents, 0);+ expect(shared.spentFraction, 1.0);+ });++ test('orphan subcategory becomes its own group', () {+ final groups = BudgetCategoryGroup.build([+ BudgetCategory.fromJson(+ budgetCategoryJson(+ id: 'bc_orphan',+ categoryId: 'cat_orphan',+ name: 'Orphan',+ parentId: 'cat_missing',+ budgetedCents: 100,+ ),+ ),+ ]);+ expect(groups, hasLength(1));+ expect(groups.single.parent.name, 'Orphan');+ });+ });++ test('spentFractionFor follows the web zero-budget rules', () {+ expect(spentFractionFor(actual: 0, total: 0), 0);+ expect(spentFractionFor(actual: 10, total: 0), 1);+ expect(spentFractionFor(actual: 0, total: 100), 0);+ expect(spentFractionFor(actual: 50, total: 100), 0.5);+ });+}diff --git a/mobile/test/providers/budgets_provider_test.dart b/mobile/test/providers/budgets_provider_test.dartnew file mode 100644index 0000000000..1007feb9e8--- /dev/null+++ b/mobile/test/providers/budgets_provider_test.dart@@ -0,0 +1,511 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:http/http.dart' as http;+import 'package:http/testing.dart';+import 'package:sure_mobile/providers/budgets_provider.dart';+import 'package:sure_mobile/services/budgets_service.dart';++import '../support/budget_fixtures.dart';++void main() {+ DateTime clock() => DateTime(2026, 10, 19);++ BudgetsProvider buildProvider({+ List<Map<String, dynamic>>? budgets,+ List<Map<String, dynamic>>? categories,+ List<http.Request>? log,+ int statusCode = 200,+ bool Function()? isOffline,+ DateTime Function()? now,+ http.Client? client,+ }) {+ return BudgetsProvider(+ service: BudgetsService(+ client: client ??+ budgetsMockClient(+ budgets: budgets,+ categories: categories,+ log: log,+ statusCode: statusCode,+ ),+ ),+ clock: now ?? clock,+ isOffline: isOffline,+ );+ }++ test('can navigate up to two years past the current month', () {+ final provider = buildProvider();+ expect(provider.month, DateTime(2026, 10));+ expect(provider.canGoNext, isTrue);++ provider.nextMonth();+ expect(provider.month, DateTime(2026, 11));++ for (var i = 0; i < 30; i++) {+ provider.nextMonth();+ }+ expect(provider.month, DateTime(2028, 10));+ expect(provider.canGoNext, isFalse);++ provider.previousMonth();+ expect(provider.month, DateTime(2028, 9));+ expect(provider.canGoNext, isTrue);+ });++ test('opens on the custom period that contains today', () async {+ final provider = buildProvider(+ now: () => DateTime(2026, 10, 10),+ budgets: [+ budgetJson(+ id: 'budget_sep',+ startDate: '2026-09-15',+ endDate: '2026-10-14',+ name: 'Sep 15 - Oct 14, 2026',+ ),+ ],+ );++ await provider.loadMonth(accessToken: 'token');++ expect(provider.month, DateTime(2026, 9));+ expect(provider.budget?.id, 'budget_sep');+ // Navigation is bounded by the current period, not the calendar month.+ for (var i = 0; i < 30; i++) {+ provider.nextMonth();+ }+ expect(provider.month, DateTime(2028, 9));+ });++ test("opens on the server's current period, not the device date", () async {+ // Device is already on April 1 (Tokyo); the family is still on March 31.+ final provider = buildProvider(+ now: () => DateTime(2027, 4, 1),+ budgets: [+ budgetJson(+ id: 'budget_apr',+ startDate: '2027-04-01',+ endDate: '2027-04-30',+ name: 'April 2027',+ current: false,+ ),+ budgetJson(+ id: 'budget_mar',+ startDate: '2027-03-01',+ endDate: '2027-03-31',+ name: 'March 2027',+ ),+ ],+ );++ await provider.loadMonth(accessToken: 'token');++ expect(provider.month, DateTime(2027, 3));+ expect(provider.budget?.id, 'budget_mar');+ });++ test('changing month drops the previous load\'s spinner and error', () async {+ final inner = budgetsMockHandler();+ final gate = Completer<void>();+ var gated = false;+ final provider = buildProvider(+ client: MockClient((request) async {+ if (gated && request.url.path.endsWith('/budgets/budget_oct')) {+ await gate.future;+ return http.Response('{"error":"boom"}', 500);+ }+ return inner(request);+ }),+ );+ await provider.loadMonth(accessToken: 'token');++ gated = true;+ final refresh =+ provider.loadMonth(accessToken: 'token', forceRefresh: true);+ await Future<void>.delayed(Duration.zero);+ expect(provider.isLoading, isTrue);++ provider.previousMonth();+ expect(provider.isLoading, isFalse);++ gate.complete();+ await refresh;+ expect(provider.month, DateTime(2026, 9));+ expect(provider.isLoading, isFalse);+ expect(provider.error, isNull);+ });++ test('a budget list is only reused for the month it was loaded for',+ () async {+ final inner = budgetsMockHandler(+ budgets: [+ budgetJson(+ id: 'budget_sep',+ startDate: '2026-09-15',+ endDate: '2026-10-14',+ name: 'Sep 15 - Oct 14, 2026',+ ),+ budgetJson(+ id: 'budget_oct',+ startDate: '2026-10-15',+ endDate: '2026-11-14',+ name: 'Oct 15 - Nov 14, 2026',+ current: false,+ ),+ budgetJson(+ id: 'budget_oct_personal',+ startDate: '2026-10-15',+ endDate: '2026-11-14',+ name: 'Oct 15 - Nov 14, 2026',+ current: false,+ ),+ ],+ );+ var failFirst = true;+ final provider = buildProvider(+ now: () => DateTime(2026, 10, 10),+ client: MockClient((request) async {+ if (failFirst) {+ failFirst = false; // the current-period lookup fails once+ return http.Response('{"error":"boom"}', 500);+ }+ return inner(request);+ }),+ );++ await provider.loadMonth(accessToken: 'token');+ expect(provider.month, DateTime(2026, 10));+ expect(provider.monthBudgets.map((b) => b.id),+ ['budget_oct', 'budget_oct_personal']);++ // Selecting retries the period lookup, which moves to September.+ await provider.selectBudget(+ accessToken: 'token',+ budgetId: 'budget_oct_personal',+ );++ expect(provider.month, DateTime(2026, 9));+ expect(provider.monthBudgets.map((b) => b.id), ['budget_sep']);+ expect(provider.budget?.id, 'budget_sep');+ });++ test('more category pages than the safety stop fail the month', () async {+ final inner = budgetsMockHandler();+ final provider = buildProvider(+ client: MockClient((request) async {+ final segments = request.url.pathSegments;+ if (segments.length == 3 && segments[2] == 'budget_categories') {+ return http.Response(+ '{"budget_categories":[],"pagination":'+ '{"page":1,"per_page":100,"total_count":100000,"total_pages":1000}}',+ 200,+ );+ }+ return inner(request);+ }),+ );++ await provider.loadMonth(accessToken: 'token');++ expect(provider.error, BudgetsLoadError.failed);+ expect(provider.hasLoadedMonth, isFalse);+ });++ test('a failed refresh keeps the month already loaded', () async {+ final inner = budgetsMockHandler();+ var fail = false;+ final provider = buildProvider(+ client: MockClient((request) async {+ if (fail) throw http.ClientException('connection reset');+ return inner(request);+ }),+ );++ await provider.loadMonth(accessToken: 'token');+ expect(provider.error, isNull);+ expect(provider.refreshFailed, isFalse);++ fail = true;+ await provider.loadMonth(accessToken: 'token', forceRefresh: true);++ expect(provider.error, BudgetsLoadError.failed);+ expect(provider.hasLoadedMonth, isTrue);+ expect(provider.refreshFailed, isTrue);+ expect(provider.categories, isNotEmpty);+ });++ test('a load that finishes after dispose does not notify', () async {+ final inner = budgetsMockHandler();+ final gate = Completer<void>();+ final provider = buildProvider(+ client: MockClient((request) async {+ await gate.future;+ return inner(request);+ }),+ );++ final load = provider.loadMonth(accessToken: 'token');+ await Future<void>.delayed(Duration.zero);+ provider.dispose();+ gate.complete();+ await load; // would throw "used after being disposed" without the guard+ });++ test('a network failure on a category line fails the month uncached',+ () async {+ final inner = budgetsMockHandler();+ var failFood = true;+ final provider = buildProvider(+ client: MockClient((request) async {+ if (failFood && request.url.path.endsWith('/bc_food')) {+ throw http.ClientException('connection reset');+ }+ return inner(request);+ }),+ );++ await provider.loadMonth(accessToken: 'token');+ expect(provider.error, BudgetsLoadError.failed);+ expect(provider.hasLoadedMonth, isFalse);++ failFood = false;+ await provider.loadMonth(accessToken: 'token');+ expect(provider.error, isNull);+ expect(provider.categories.every((c) => c.hasDerivedAmounts), isTrue);+ });++ test('a missing category line keeps its budgeted amount', () async {+ final inner = budgetsMockHandler();+ final provider = buildProvider(+ client: MockClient((request) async {+ if (request.url.path.endsWith('/bc_transport')) {+ return http.Response('{"error":"not_found"}', 404);+ }+ return inner(request);+ }),+ );+ await provider.loadMonth(accessToken: 'token');++ expect(provider.error, isNull);+ final transport =+ provider.categories.firstWhere((c) => c.name == 'Transport');+ expect(transport.hasDerivedAmounts, isFalse);+ expect(transport.budgetedSpendingCents, 30000);+ });++ test('shows the loading state while the current period resolves', () async {+ final inner = budgetsMockHandler();+ final gate = Completer<void>();+ var calls = 0;+ final provider = buildProvider(+ client: MockClient((request) async {+ if (calls++ == 0) await gate.future;+ return inner(request);+ }),+ );++ final load = provider.loadMonth(accessToken: 'token');+ await Future<void>.delayed(Duration.zero);+ expect(provider.isLoading, isTrue);+ expect(provider.hasLoadedMonth, isFalse);++ gate.complete();+ await load;+ expect(provider.isLoading, isFalse);+ expect(provider.hasLoadedMonth, isTrue);+ });++ test('returning to a cached month clears a pending load', () async {+ final inner = budgetsMockHandler();+ final gate = Completer<void>();+ var gateSeptember = false;+ final provider = buildProvider(+ client: MockClient((request) async {+ if (gateSeptember &&+ request.url.queryParameters['start_date'] == '2026-09-01') {+ await gate.future;+ }+ return inner(request);+ }),+ );+ await provider.loadMonth(accessToken: 'token');++ gateSeptember = true;+ provider.previousMonth();+ final september = provider.loadMonth(accessToken: 'token');+ await Future<void>.delayed(Duration.zero);+ expect(provider.isLoading, isTrue);++ provider.nextMonth();+ await provider.loadMonth(accessToken: 'token');+ expect(provider.isLoading, isFalse);+ expect(provider.budget?.id, 'budget_oct');++ gate.complete();+ await september;+ expect(provider.isLoading, isFalse);+ });++ test('markUnauthorized shows the session-expired state', () {+ final provider = buildProvider();+ provider.markUnauthorized();+ expect(provider.error, BudgetsLoadError.unauthorized);+ expect(provider.isLoading, isFalse);+ });++ test('assembles a month from the budget and category endpoints', () async {+ final log = <http.Request>[];+ final provider = buildProvider(log: log);++ await provider.loadMonth(accessToken: 'token');++ expect(provider.error, isNull);+ expect(provider.budget?.actualSpending, r'$1,500.00');+ expect(provider.categories, hasLength(5));+ expect(provider.categories.every((c) => c.hasDerivedAmounts), isTrue);++ // Gifts (no budget, no spending) is hidden; Food keeps both children.+ final groups = provider.visibleGroups;+ expect(groups.map((g) => g.parent.name), ['Food', 'Transport']);+ expect(groups.first.children.map((c) => c.name), [+ 'Groceries',+ 'Restaurants',+ ]);+ expect(provider.overBudgetCount, 1);++ // current period lookup, then list + show budget + list categories ++ // one show per category+ expect(log, hasLength(1 + 3 + 5));+ expect(log.first.url.queryParameters['start_date'], '2026-09-01');+ expect(log.first.url.queryParameters['end_date'], '2026-11-30');+ expect(log[1].url.queryParameters['start_date'], '2026-10-01');+ expect(log[1].url.queryParameters['end_date'], '2026-11-30');+ });++ test('an uninitialized budget lists every category', () async {+ final provider = buildProvider(budgets: [budgetJson(initialized: false)]);++ await provider.loadMonth(accessToken: 'token');++ expect(provider.showsAllCategories, isTrue);+ expect(provider.visibleGroups.map((g) => g.parent.name),+ containsAll(['Food', 'Transport', 'Gifts']));+ });++ test('uses the in-memory copy unless forced', () async {+ final log = <http.Request>[];+ final provider = buildProvider(log: log);++ await provider.loadMonth(accessToken: 'token');+ final first = log.length;+ await provider.loadMonth(accessToken: 'token');+ expect(log.length, first);++ await provider.loadMonth(accessToken: 'token', forceRefresh: true);+ // The current period is looked up only once.+ expect(log.length - first, 3 + 5);+ });++ test('matches a custom month start budget by its start month', () async {+ final provider = buildProvider(+ budgets: [+ budgetJson(+ id: 'budget_sep',+ startDate: '2026-09-15',+ endDate: '2026-10-14',+ current: false, // today (Oct 19) is in the October period+ ),+ budgetJson(+ id: 'budget_oct',+ startDate: '2026-10-15',+ endDate: '2026-11-14',+ name: 'Oct 15 - Nov 14, 2026',+ ),+ ],+ );++ await provider.loadMonth(accessToken: 'token');+ expect(provider.monthBudgets.map((b) => b.id), ['budget_oct']);+ expect(provider.budget?.name, 'Oct 15 - Nov 14, 2026');+ });++ test('a month with no budget is empty, not an error', () async {+ final provider = buildProvider(budgets: []);+ await provider.loadMonth(accessToken: 'token');++ expect(provider.error, isNull);+ expect(provider.hasLoadedMonth, isTrue);+ expect(provider.budget, isNull);+ });++ test('switches between several budgets in the same month', () async {+ final provider = buildProvider(+ budgets: [+ budgetJson(id: 'budget_oct'),+ budgetJson(id: 'budget_oct_personal', actualCents: 1000),+ ],+ );++ await provider.loadMonth(accessToken: 'token');+ expect(provider.monthBudgets, hasLength(2));+ expect(provider.budget?.id, 'budget_oct');++ await provider.selectBudget(+ accessToken: 'token',+ budgetId: 'budget_oct_personal',+ );+ expect(provider.budget?.id, 'budget_oct_personal');+ expect(provider.budget?.actualSpending, r'$10.00');+ });++ test('switching budgets does not refetch the month list', () async {+ final log = <http.Request>[];+ final provider = buildProvider(+ log: log,+ budgets: [+ budgetJson(id: 'budget_oct'),+ budgetJson(id: 'budget_oct_personal', actualCents: 1000),+ ],+ );+ await provider.loadMonth(accessToken: 'token');+ log.clear();++ await provider.selectBudget(+ accessToken: 'token',+ budgetId: 'budget_oct_personal',+ );+ expect(provider.budget?.id, 'budget_oct_personal');+ expect(provider.monthBudgets, hasLength(2));+ expect(log.where((r) => r.url.path.endsWith('/api/v1/budgets')), isEmpty);+ expect(log, isNotEmpty);+ });++ test('401 surfaces as unauthorized', () async {+ final provider = buildProvider(statusCode: 401);+ await provider.loadMonth(accessToken: 'token');+ expect(provider.error, BudgetsLoadError.unauthorized);+ });++ test('offline without a loaded month reports offline', () async {+ final log = <http.Request>[];+ final provider = buildProvider(log: log, isOffline: () => true);+ await provider.loadMonth(accessToken: 'token');++ expect(provider.error, BudgetsLoadError.offline);+ expect(log, isEmpty);+ });++ test('offline keeps showing a month loaded earlier', () async {+ var offline = false;+ final provider = buildProvider(isOffline: () => offline);+ await provider.loadMonth(accessToken: 'token');++ offline = true;+ await provider.loadMonth(accessToken: 'token', forceRefresh: true);++ expect(provider.error, isNull);+ expect(provider.showingCachedWhileOffline, isTrue);+ expect(provider.budget?.id, 'budget_oct');+ });+}diff --git a/mobile/test/screens/budget_category_transactions_screen_test.dart b/mobile/test/screens/budget_category_transactions_screen_test.dartnew file mode 100644index 0000000000..2254450e0d--- /dev/null+++ b/mobile/test/screens/budget_category_transactions_screen_test.dart@@ -0,0 +1,86 @@+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:sure_mobile/l10n/app_localizations.dart';+import 'package:sure_mobile/providers/privacy_provider.dart';+import 'package:sure_mobile/screens/budget_category_transactions_screen.dart';+import 'package:sure_mobile/services/transactions_service.dart';+import 'package:sure_mobile/theme/sure_theme.dart';++String _page(String name, {required int page, required int pages}) =>+ '{"transactions":[{"id":"$name","account":{"id":"a1"},"name":"$name",'+ '"date":"2026-10-03","amount":"\$1.00","currency":"USD",'+ '"classification":"expense",'+ '"category":{"id":"cat_food","name":"Food"}}],'+ '"pagination":{"page":$page,"per_page":50,"total_count":2,'+ '"total_pages":$pages}}';++void main() {+ Widget harness(+ TransactionsService service, {+ Future<String?> Function()? loader,+ }) {+ return ChangeNotifierProvider<PrivacyProvider>(+ create: (_) => PrivacyProvider(initialHidden: false),+ child: MaterialApp(+ theme: SureTheme.light,+ localizationsDelegates: AppLocalizations.localizationsDelegates,+ supportedLocales: AppLocalizations.supportedLocales,+ home: BudgetCategoryTransactionsScreen(+ title: 'Food',+ periodLabel: 'October 2026',+ categoryIds: const ['cat_food'],+ startDate: DateTime(2026, 10, 1),+ endDate: DateTime(2026, 10, 31),+ service: service,+ accessTokenLoader: loader ?? () async => 'token',+ ),+ ),+ );+ }++ testWidgets('without an access token shows the error state, not empty',+ (tester) async {+ final service = TransactionsService(+ client: MockClient((_) async => http.Response('{}', 500)),+ );+ await tester.pumpWidget(harness(service, loader: () async => null));+ await tester.pumpAndSettle();++ expect(find.text("Couldn't load transactions"), findsOneWidget);+ expect(find.text('Try Again'), findsOneWidget);+ expect(find.textContaining('No transactions'), findsNothing);+ });++ testWidgets('retrying a failed refresh reloads page one', (tester) async {+ final pages = <String>[];+ var failNext = false;+ final service = TransactionsService(+ client: MockClient((request) async {+ final page = request.url.queryParameters['page']!;+ pages.add(page);+ if (failNext) {+ failNext = false;+ return http.Response('{}', 500);+ }+ return http.Response(_page('Row $page', page: 1, pages: 2), 200);+ }),+ );+ await tester.pumpWidget(harness(service));+ await tester.pumpAndSettle();+ expect(pages, ['1']);++ failNext = true;+ await tester.fling(find.text('Row 1'), const Offset(0, 400), 1000);+ await tester.pumpAndSettle();+ expect(pages, ['1', '1']);+ expect(find.text('Try Again'), findsOneWidget);++ await tester.tap(find.text('Try Again'));+ await tester.pumpAndSettle();+ expect(pages, ['1', '1', '1']);+ expect(find.text('Row 1'), findsOneWidget);+ });+}diff --git a/mobile/test/screens/budgets_screen_test.dart b/mobile/test/screens/budgets_screen_test.dartnew file mode 100644index 0000000000..efbb86d75a--- /dev/null+++ b/mobile/test/screens/budgets_screen_test.dart@@ -0,0 +1,249 @@+import 'package:flutter/material.dart';+import 'package:flutter_localizations/flutter_localizations.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/providers/budgets_provider.dart';+import 'package:sure_mobile/providers/privacy_provider.dart';+import 'package:sure_mobile/screens/budget_category_transactions_screen.dart';+import 'package:sure_mobile/screens/budgets_screen.dart';+import 'package:sure_mobile/services/budgets_service.dart';+import 'package:sure_mobile/services/preferences_service.dart';+import 'package:sure_mobile/theme/sure_theme.dart';+import 'package:sure_mobile/widgets/budget_category_row.dart';+import 'package:sure_mobile/widgets/budget_progress_bar.dart';++import '../support/budget_fixtures.dart';++void main() {+ setUp(() {+ SharedPreferences.setMockInitialValues({});+ PreferencesService.resetForTest();+ });++ BudgetsProvider buildProvider({List<Map<String, dynamic>>? budgets}) {+ return BudgetsProvider(+ service: BudgetsService(client: budgetsMockClient(budgets: budgets)),+ clock: () => DateTime(2026, 10, 19),+ );+ }++ Widget harness(+ BudgetsProvider provider, {+ required bool hidden,+ Future<String?> Function()? loader,+ Locale locale = const Locale('en'),+ }) {+ return ChangeNotifierProvider<PrivacyProvider>(+ create: (_) => PrivacyProvider(initialHidden: hidden),+ child: MaterialApp(+ theme: SureTheme.light,+ locale: locale,+ supportedLocales: AppLocalizations.supportedLocales,+ localizationsDelegates: const [+ AppLocalizations.delegate,+ GlobalMaterialLocalizations.delegate,+ GlobalWidgetsLocalizations.delegate,+ GlobalCupertinoLocalizations.delegate,+ ],+ home: BudgetsScreen(+ provider: provider,+ accessTokenLoader: loader ?? () async => 'token',+ ),+ ),+ );+ }++ Future<void> pumpScreen(+ WidgetTester tester,+ BudgetsProvider provider, {+ bool hidden = false,+ Future<String?> Function()? loader,+ Locale locale = const Locale('en'),+ }) async {+ tester.view.physicalSize = const Size(1080, 2400);+ tester.view.devicePixelRatio = 2.5;+ addTearDown(tester.view.reset);+ await tester.pumpWidget(+ harness(provider, hidden: hidden, loader: loader, locale: locale),+ );+ await tester.pumpAndSettle();+ }++ testWidgets('shows totals, nested categories and over-budget state',+ (tester) async {+ await pumpScreen(tester, buildProvider());++ expect(find.text('October 2026'), findsOneWidget);+ expect(find.text('Budgeted'), findsOneWidget);+ expect(find.text(r'$2,000.00'), findsOneWidget);+ expect(find.text(r'$1,500.00'), findsOneWidget);+ expect(find.text(r'$500.00'), findsOneWidget);++ expect(find.byType(BudgetCategoryRow), findsNWidgets(4));+ expect(find.text('Gifts'), findsNothing);+ expect(find.text('Groceries'), findsOneWidget);+ expect(find.text(r'$120.00 over'), findsOneWidget);+ expect(find.text('Over budget'), findsOneWidget);+ expect(find.text('Near limit'), findsOneWidget);+ expect(find.text('Shared budget'), findsOneWidget);+ expect(find.text(r'+$50.00 rolled over'), findsOneWidget);++ // Planned future months stay reachable from the current month.+ final next = tester.widget<IconButton>(+ find.widgetWithIcon(IconButton, Icons.chevron_right),+ );+ expect(next.onPressed, isNotNull);+ });++ testWidgets('over-budget filter shows only over-budget lines',+ (tester) async {+ await pumpScreen(tester, buildProvider());++ await tester.tap(find.text('Over budget (1)'));+ await tester.pumpAndSettle();++ expect(find.byType(BudgetCategoryRow), findsOneWidget);+ expect(find.text('Groceries'), findsOneWidget);+ expect(find.text('Transport'), findsNothing);+ });++ testWidgets('privacy mode masks every amount', (tester) async {+ await pumpScreen(tester, buildProvider(), hidden: true);++ expect(find.text(r'$2,000.00'), findsNothing);+ expect(find.textContaining(r'$1,500.00'), findsNothing);+ expect(find.text(r'$••••'), findsWidgets);+ expect(find.text(r'$•••• over'), findsOneWidget);+ // The bars would give the share spent away.+ final bars =+ tester.widgetList<BudgetProgressBar>(find.byType(BudgetProgressBar));+ expect(bars, isNotEmpty);+ expect(bars.every((bar) => bar.hidden), isTrue);+ });++ testWidgets('formats the month in Swedish without extra date setup',+ (tester) async {+ await pumpScreen(+ tester,+ buildProvider(budgets: []),+ locale: const Locale('sv'),+ );++ expect(tester.takeException(), isNull);+ expect(find.textContaining('oktober 2026'), findsWidgets);+ });++ testWidgets('month without a budget shows the empty state', (tester) async {+ await pumpScreen(tester, buildProvider(budgets: []));++ expect(find.text('No budget for October 2026'), findsOneWidget);+ expect(find.byType(BudgetCategoryRow), findsNothing);+ });++ testWidgets('previous month loads that month', (tester) async {+ await pumpScreen(tester, buildProvider());++ await tester.tap(find.byTooltip('Previous month'));+ await tester.pumpAndSettle();++ expect(find.text('No budget for September 2026'), findsOneWidget);+ final next = tester.widget<IconButton>(+ find.widgetWithIcon(IconButton, Icons.chevron_right),+ );+ expect(next.onPressed, isNotNull);+ });++ testWidgets('tapping a parent opens its transactions with subcategories',+ (tester) async {+ await pumpScreen(tester, buildProvider());++ await tester.tap(find.text('Food'));+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 400));++ final screen = tester.widget<BudgetCategoryTransactionsScreen>(+ find.byType(BudgetCategoryTransactionsScreen),+ );+ expect(screen.categoryIds, [+ 'cat_food',+ 'cat_groceries',+ 'cat_restaurants',+ ]);+ expect(screen.startDate, DateTime(2026, 10, 1));+ expect(screen.endDate, DateTime(2026, 10, 31));+ });++ testWidgets('a failed refresh keeps the loaded month with a banner',+ (tester) async {+ final inner = budgetsMockHandler();+ var fail = false;+ final provider = BudgetsProvider(+ service: BudgetsService(+ client: MockClient((request) async {+ if (fail) throw http.ClientException('connection reset');+ return inner(request);+ }),+ ),+ clock: () => DateTime(2026, 10, 19),+ );+ await pumpScreen(tester, provider);+ expect(find.text('Budgeted'), findsOneWidget);++ fail = true;+ await provider.loadMonth(accessToken: 'token', forceRefresh: true);+ await tester.pumpAndSettle();++ expect(find.text("Couldn't load budgets"), findsNothing);+ expect(find.text('Budgeted'), findsOneWidget);+ expect(+ find.text("Couldn't refresh. Showing the figures loaded earlier."),+ findsOneWidget,+ );++ fail = false;+ await tester.tap(find.text('Try Again'));+ await tester.pumpAndSettle();+ expect(+ find.text("Couldn't refresh. Showing the figures loaded earlier."),+ findsNothing,+ );+ });++ testWidgets('without an access token shows the session-expired state',+ (tester) async {+ await pumpScreen(tester, buildProvider(), loader: () async => null);++ expect(+ find.text('Your session has expired. Please sign in again.'),+ findsOneWidget,+ );+ });++ testWidgets('switching budgets after the session expired says so',+ (tester) async {+ String? token = 'token';+ await pumpScreen(+ tester,+ buildProvider(+ budgets: [+ budgetJson(id: 'budget_oct'),+ budgetJson(id: 'budget_oct_personal', actualCents: 1000),+ ],+ ),+ loader: () async => token,+ );++ token = null;+ await tester.tap(find.text('Budget 2'));+ await tester.pumpAndSettle();++ expect(+ find.text('Your session has expired. Please sign in again.'),+ findsOneWidget,+ );+ });+}diff --git a/mobile/test/services/budgets_service_test.dart b/mobile/test/services/budgets_service_test.dartnew file mode 100644index 0000000000..faa78263c5--- /dev/null+++ b/mobile/test/services/budgets_service_test.dart@@ -0,0 +1,127 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:http/http.dart' as http;+import 'package:http/testing.dart';+import 'package:sure_mobile/models/budget.dart';+import 'package:sure_mobile/services/budgets_service.dart';+import 'package:sure_mobile/services/transactions_service.dart';++import '../support/budget_fixtures.dart';++void main() {+ group('BudgetsService', () {+ test('lists budgets with date filters', () async {+ final requests = <http.Request>[];+ final service = BudgetsService(+ client: budgetsMockClient(log: requests),+ );++ final result = await service.getBudgets(+ accessToken: 'token',+ startDate: DateTime(2026, 10, 1),+ endDate: DateTime(2026, 11, 30),+ perPage: 100,+ );++ expect(result['success'], isTrue);+ final budgets = result['budgets'] as List<Budget>;+ expect(budgets.single.id, 'budget_oct');+ expect(budgets.single.hasDerivedAmounts, isFalse);++ final url = requests.single.url;+ expect(url.path, '/api/v1/budgets');+ expect(url.queryParameters['start_date'], '2026-10-01');+ expect(url.queryParameters['end_date'], '2026-11-30');+ expect(url.queryParameters['per_page'], '100');+ });++ test('fetches a budget with derived amounts', () async {+ final service = BudgetsService(client: budgetsMockClient());+ final result = await service.getBudget(+ accessToken: 'token',+ id: 'budget_oct',+ );++ expect(result['success'], isTrue);+ final budget = result['budget'] as Budget;+ expect(budget.actualSpending, r'$1,500.00');+ });++ test('lists budget categories for a budget', () async {+ final requests = <http.Request>[];+ final service = BudgetsService(+ client: budgetsMockClient(log: requests),+ );++ final result = await service.getBudgetCategories(+ accessToken: 'token',+ budgetId: 'budget_oct',+ );++ expect(result['success'], isTrue);+ final categories = result['budget_categories'] as List<BudgetCategory>;+ expect(categories, hasLength(5));+ expect(categories.first.hasDerivedAmounts, isFalse);+ expect(requests.single.url.queryParameters['budget_id'], 'budget_oct');+ });++ test('fetches one budget category with actual spending', () async {+ final service = BudgetsService(client: budgetsMockClient());+ final result = await service.getBudgetCategory(+ accessToken: 'token',+ id: 'bc_groceries',+ );++ final bc = result['budget_category'] as BudgetCategory;+ expect(bc.actualSpendingCents, 52000);+ expect(bc.availableToSpend, r'-$120.00');+ });++ test('maps 401 to unauthorized', () async {+ final service = BudgetsService(+ client: budgetsMockClient(statusCode: 401),+ );+ final result = await service.getBudgets(accessToken: 'token');+ expect(result, {'success': false, 'error': 'unauthorized'});+ });++ test('reports server error message', () async {+ final service = BudgetsService(+ client: budgetsMockClient(statusCode: 500),+ );+ final result = await service.getBudget(accessToken: 'token', id: 'x');+ expect(result['success'], isFalse);+ expect(result['error'], 'nope');+ });+ });++ test('TransactionsService filters by categories and date range', () async {+ late Uri captured;+ final service = TransactionsService(+ client: MockClient((request) async {+ captured = request.url;+ return http.Response(+ '{"transactions":[],"pagination":{"page":1,"total_pages":1}}',+ 200,+ );+ }),+ );++ final result = await service.getTransactions(+ accessToken: 'token',+ categoryIds: ['cat_food', 'cat_groceries'],+ startDate: '2026-10-01',+ endDate: '2026-10-31',+ page: 1,+ perPage: 50,+ );++ expect(result['success'], isTrue);+ expect(captured.queryParametersAll['category_ids[]'], [+ 'cat_food',+ 'cat_groceries',+ ]);+ expect(captured.queryParameters['start_date'], '2026-10-01');+ expect(captured.queryParameters['end_date'], '2026-10-31');+ expect(captured.queryParameters.containsKey('account_id'), isFalse);+ });+}diff --git a/mobile/test/support/budget_fixtures.dart b/mobile/test/support/budget_fixtures.dartnew file mode 100644index 0000000000..62f9c777a6--- /dev/null+++ b/mobile/test/support/budget_fixtures.dart@@ -0,0 +1,254 @@+import 'dart:convert';++import 'package:http/http.dart' as http;+import 'package:http/testing.dart';++/// JSON fixtures shaped like the `/api/v1/budgets` and+/// `/api/v1/budget_categories` jbuilder views, plus a [MockClient] that routes+/// requests to them.++Map<String, dynamic> budgetJson({+ String id = 'budget_oct',+ String startDate = '2026-10-01',+ String endDate = '2026-10-31',+ String name = 'October 2026',+ bool initialized = true,+ bool current = true,+ bool withDerived = true,+ int budgetedCents = 200000,+ int actualCents = 150000,+ int availableCents = 50000,+}) {+ return {+ 'id': id,+ 'start_date': startDate,+ 'end_date': endDate,+ 'name': name,+ 'currency': 'USD',+ 'initialized': initialized,+ 'current': current,+ 'budgeted_spending': initialized ? _usd(budgetedCents) : null,+ 'budgeted_spending_cents': initialized ? budgetedCents : null,+ 'expected_income': r'$5,000.00',+ 'expected_income_cents': 500000,+ 'allocated_spending': _usd(budgetedCents),+ 'allocated_spending_cents': budgetedCents,+ if (withDerived) ...{+ 'actual_spending': _usd(actualCents),+ 'actual_spending_cents': actualCents,+ 'actual_income': r'$5,200.00',+ 'actual_income_cents': 520000,+ 'available_to_spend': _usd(availableCents),+ 'available_to_spend_cents': availableCents,+ 'available_to_allocate': r'$0.00',+ 'available_to_allocate_cents': 0,+ },+ 'created_at': '2026-10-01T00:00:00Z',+ 'updated_at': '2026-10-01T00:00:00Z',+ };+}++Map<String, dynamic> budgetCategoryJson({+ required String id,+ required String categoryId,+ required String name,+ String budgetId = 'budget_oct',+ String? parentId,+ int budgetedCents = 0,+ int? displayBudgetedCents,+ int actualCents = 0,+ int rolledOverCents = 0,+ int? availableCents,+ bool inheritsParent = false,+ bool withDerived = true,+ String color = '#e99537',+}) {+ final display = displayBudgetedCents ?? budgetedCents;+ final available =+ availableCents ?? (budgetedCents + rolledOverCents - actualCents);+ return {+ 'id': id,+ 'budget_id': budgetId,+ 'currency': 'USD',+ 'subcategory': parentId != null,+ 'inherits_parent_budget': inheritsParent,+ 'rollover_enabled': rolledOverCents > 0,+ 'budgeted_spending': _usd(budgetedCents),+ 'budgeted_spending_cents': budgetedCents,+ 'display_budgeted_spending': _usd(display),+ 'display_budgeted_spending_cents': display,+ if (withDerived) ...{+ 'actual_spending': _usd(actualCents),+ 'actual_spending_cents': actualCents,+ 'rolled_over_amount': _usd(rolledOverCents),+ 'rolled_over_amount_cents': rolledOverCents,+ 'available_to_spend': _usd(available),+ 'available_to_spend_cents': available,+ },+ 'category': {+ 'id': categoryId,+ 'name': name,+ 'color': color,+ 'lucide_icon': 'shapes',+ 'parent_id': parentId,+ },+ 'created_at': '2026-10-01T00:00:00Z',+ 'updated_at': '2026-10-01T00:00:00Z',+ };+}++/// A month with a parent (Food) and two subcategories (Groceries with its own+/// limit and over budget, Restaurants sharing Food's budget), plus Transport+/// (on track) and Gifts (no budget, no spending — hidden).+List<Map<String, dynamic>> octoberCategories() => [+ budgetCategoryJson(+ id: 'bc_food',+ categoryId: 'cat_food',+ name: 'Food',+ budgetedCents: 80000,+ actualCents: 76000,+ ),+ budgetCategoryJson(+ id: 'bc_gifts',+ categoryId: 'cat_gifts',+ name: 'Gifts',+ ),+ budgetCategoryJson(+ id: 'bc_groceries',+ categoryId: 'cat_groceries',+ name: 'Groceries',+ parentId: 'cat_food',+ budgetedCents: 40000,+ actualCents: 52000,+ ),+ budgetCategoryJson(+ id: 'bc_restaurants',+ categoryId: 'cat_restaurants',+ name: 'Restaurants',+ parentId: 'cat_food',+ inheritsParent: true,+ displayBudgetedCents: 80000,+ actualCents: 24000,+ availableCents: 0,+ ),+ budgetCategoryJson(+ id: 'bc_transport',+ categoryId: 'cat_transport',+ name: 'Transport',+ budgetedCents: 30000,+ actualCents: 12000,+ rolledOverCents: 5000,+ color: '#4da568',+ ),+ ];++/// Routes budget API requests to [budgets] / [categories] and records each+/// request in [log].+MockClient budgetsMockClient({+ List<Map<String, dynamic>>? budgets,+ List<Map<String, dynamic>>? categories,+ List<http.Request>? log,+ int statusCode = 200,+}) =>+ MockClient(budgetsMockHandler(+ budgets: budgets,+ categories: categories,+ log: log,+ statusCode: statusCode,+ ));++/// The request handler behind [budgetsMockClient], for tests that wrap it.+Future<http.Response> Function(http.Request) budgetsMockHandler({+ List<Map<String, dynamic>>? budgets,+ List<Map<String, dynamic>>? categories,+ List<http.Request>? log,+ int statusCode = 200,+}) {+ final budgetList = budgets ?? [budgetJson()];+ final categoryList = categories ?? octoberCategories();++ return (request) async {+ log?.add(request);+ if (statusCode != 200) {+ return http.Response('{"error":"nope"}', statusCode);+ }+ final segments = request.url.pathSegments;+ final resource = segments.length >= 3 ? segments[2] : '';+ final id = segments.length >= 4 ? segments[3] : null;++ if (resource == 'budgets') {+ if (id == null) {+ final stripped = budgetList.map(_withoutDerived).toList();+ return _json({+ 'budgets': stripped,+ 'pagination': _pagination(stripped.length),+ });+ }+ final match = budgetList.where((b) => b['id'] == id);+ return match.isEmpty+ ? http.Response('{"error":"not_found"}', 404)+ : _json(match.first);+ }++ if (resource == 'budget_categories') {+ if (id == null) {+ final budgetId = request.url.queryParameters['budget_id'];+ final filtered = categoryList+ .where((c) => budgetId == null || c['budget_id'] == budgetId)+ .map(_withoutDerived)+ .toList();+ return _json({+ 'budget_categories': filtered,+ 'pagination': _pagination(filtered.length),+ });+ }+ final match = categoryList.where((c) => c['id'] == id);+ return match.isEmpty+ ? http.Response('{"error":"not_found"}', 404)+ : _json(match.first);+ }++ return http.Response('{"error":"unexpected"}', 500);+ };+}++const _derivedKeys = {+ 'actual_spending',+ 'actual_spending_cents',+ 'actual_income',+ 'actual_income_cents',+ 'available_to_spend',+ 'available_to_spend_cents',+ 'available_to_allocate',+ 'available_to_allocate_cents',+ 'rolled_over_amount',+ 'rolled_over_amount_cents',+};++Map<String, dynamic> _withoutDerived(Map<String, dynamic> json) =>+ Map.of(json)..removeWhere((key, _) => _derivedKeys.contains(key));++Map<String, dynamic> _pagination(int count) => {+ 'page': 1,+ 'per_page': 100,+ 'total_count': count,+ 'total_pages': 1,+ };++http.Response _json(Object body) => http.Response(+ jsonEncode(body),+ 200,+ headers: {'content-type': 'application/json; charset=utf-8'},+ );++String _usd(int cents) {+ final negative = cents < 0;+ final abs = cents.abs();+ final dollars = abs ~/ 100;+ final rem = (abs % 100).toString().padLeft(2, '0');+ final grouped = dollars.toString().replaceAllMapped(+ RegExp(r'\B(?=(\d{3})+(?!\d))'),+ (_) => ',',+ );+ return '${negative ? '-' : ''}\$$grouped.$rem';+}