Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(mobile): cash flow and spending by category (#4428)

Bhargav Mehtaefe28a8004f3
diff --git a/mobile/lib/l10n/app_en.arb b/mobile/lib/l10n/app_en.arb
index de26376f33..15a14a72ca 100644
--- a/mobile/lib/l10n/app_en.arb
+++ b/mobile/lib/l10n/app_en.arb
@@ -1103,5 +1103,92 @@
"@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." }
+ "@budgetCategoryTransactionsLoadFailed": { "description": "Shown when a budget category's transactions fail to load." },
+
+"moreCashFlow": "Cash Flow",
+ "@moreCashFlow": { "description": "Menu item title for the Cash Flow report in the More screen." },
+
+"moreCashFlowSubtitle": "Income, spending and savings by category",
+ "@moreCashFlowSubtitle": { "description": "Subtitle for the Cash Flow menu item in the More screen." },
+
+"cashFlowTitle": "Cash Flow",
+ "@cashFlowTitle": { "description": "App bar title of the Cash Flow report screen." },
+
+"cashFlowPeriodCurrentMonth": "This month",
+ "@cashFlowPeriodCurrentMonth": { "description": "Period chip: the current month (web MTD), or the whole current custom month when the family has a custom month start day." },
+
+"cashFlowPeriodLastMonth": "Last month",
+ "@cashFlowPeriodLastMonth": { "description": "Period chip: the previous month (web LM), following the family's custom month start day when set." },
+
+"cashFlowPeriodLast30Days": "Last 30 days",
+ "@cashFlowPeriodLast30Days": { "description": "Period chip: last 30 days (web 30D)." },
+
+"cashFlowPeriodLast90Days": "Last 90 days",
+ "@cashFlowPeriodLast90Days": { "description": "Period chip: last 90 days (web 90D)." },
+
+"cashFlowPeriodCurrentYear": "Year to date",
+ "@cashFlowPeriodCurrentYear": { "description": "Period chip: current year to date (web YTD)." },
+
+"cashFlowPeriodLast365Days": "Last 365 days",
+ "@cashFlowPeriodLast365Days": { "description": "Period chip: last 365 days (web 365D)." },
+
+"cashFlowIncome": "Income",
+ "@cashFlowIncome": { "description": "Summary label and segment label for income." },
+
+"cashFlowExpenses": "Expenses",
+ "@cashFlowExpenses": { "description": "Summary label and segment label for expenses." },
+
+"cashFlowNetSavings": "Net savings",
+ "@cashFlowNetSavings": { "description": "Summary label for income minus expenses." },
+
+"cashFlowSavingsRate": "{rate} savings rate",
+ "@cashFlowSavingsRate": {
+ "description": "Savings rate shown under net savings, e.g. '18.2% savings rate'.",
+ "placeholders": { "rate": { "type": "String", "example": "18.2%" } }
+ },
+
+"cashFlowExpensesByCategory": "Expenses by category",
+ "@cashFlowExpensesByCategory": { "description": "Section header for the expense category chart and list." },
+
+"cashFlowIncomeByCategory": "Income by category",
+ "@cashFlowIncomeByCategory": { "description": "Section header for the income category chart and list." },
+
+"cashFlowShareOfExpenses": "{percent} of expenses",
+ "@cashFlowShareOfExpenses": {
+ "description": "Category row subtitle with its share of total expenses.",
+ "placeholders": { "percent": { "type": "String", "example": "24.5%" } }
+ },
+
+"cashFlowShareOfIncome": "{percent} of income",
+ "@cashFlowShareOfIncome": {
+ "description": "Category row subtitle with its share of total income.",
+ "placeholders": { "percent": { "type": "String", "example": "80%" } }
+ },
+
+"cashFlowEmpty": "No income or expenses in this period",
+ "@cashFlowEmpty": { "description": "Empty state title when the period has no categorized cash flow." },
+
+"cashFlowEmptySubtitle": "Try another period or pull to refresh.",
+ "@cashFlowEmptySubtitle": { "description": "Empty state subtitle on the Cash Flow screen." },
+
+"cashFlowNoExpenses": "No expenses in this period",
+ "@cashFlowNoExpenses": { "description": "Shown in the category section when the expense side is empty." },
+
+"cashFlowNoIncome": "No income in this period",
+ "@cashFlowNoIncome": { "description": "Shown in the category section when the income side is empty." },
+
+"cashFlowLoadFailed": "Couldn't load cash flow",
+ "@cashFlowLoadFailed": { "description": "Error state title when the cash flow request fails." },
+
+"cashFlowOffline": "You're offline. Cash flow is calculated by your Sure server, so it needs a connection.",
+ "@cashFlowOffline": { "description": "Error state message when the device is offline and no report is loaded." },
+
+"cashFlowOutdated": "Outdated",
+ "@cashFlowOutdated": { "description": "Badge shown when the displayed report could not be refreshed." },
+
+"cashFlowTransactionsEmpty": "No transactions in this period",
+ "@cashFlowTransactionsEmpty": { "description": "Empty state of the category transactions screen." },
+
+"cashFlowTransactionsLoadFailed": "Couldn't load transactions",
+ "@cashFlowTransactionsLoadFailed": { "description": "Error state of the category transactions screen." }
}
diff --git a/mobile/lib/l10n/app_localizations.dart b/mobile/lib/l10n/app_localizations.dart
index 3f63522389..4ddad5a096 100644
--- a/mobile/lib/l10n/app_localizations.dart
+++ b/mobile/lib/l10n/app_localizations.dart
@@ -2119,6 +2119,162 @@ abstract class AppLocalizations {
/// In en, this message translates to:
/// **'Couldn\'t load transactions'**
String get budgetCategoryTransactionsLoadFailed;
+
+ /// Menu item title for the Cash Flow report in the More screen.
+ ///
+ /// In en, this message translates to:
+ /// **'Cash Flow'**
+ String get moreCashFlow;
+
+ /// Subtitle for the Cash Flow menu item in the More screen.
+ ///
+ /// In en, this message translates to:
+ /// **'Income, spending and savings by category'**
+ String get moreCashFlowSubtitle;
+
+ /// App bar title of the Cash Flow report screen.
+ ///
+ /// In en, this message translates to:
+ /// **'Cash Flow'**
+ String get cashFlowTitle;
+
+ /// Period chip: the current month (web MTD), or the whole current custom month when the family has a custom month start day.
+ ///
+ /// In en, this message translates to:
+ /// **'This month'**
+ String get cashFlowPeriodCurrentMonth;
+
+ /// Period chip: the previous month (web LM), following the family's custom month start day when set.
+ ///
+ /// In en, this message translates to:
+ /// **'Last month'**
+ String get cashFlowPeriodLastMonth;
+
+ /// Period chip: last 30 days (web 30D).
+ ///
+ /// In en, this message translates to:
+ /// **'Last 30 days'**
+ String get cashFlowPeriodLast30Days;
+
+ /// Period chip: last 90 days (web 90D).
+ ///
+ /// In en, this message translates to:
+ /// **'Last 90 days'**
+ String get cashFlowPeriodLast90Days;
+
+ /// Period chip: current year to date (web YTD).
+ ///
+ /// In en, this message translates to:
+ /// **'Year to date'**
+ String get cashFlowPeriodCurrentYear;
+
+ /// Period chip: last 365 days (web 365D).
+ ///
+ /// In en, this message translates to:
+ /// **'Last 365 days'**
+ String get cashFlowPeriodLast365Days;
+
+ /// Summary label and segment label for income.
+ ///
+ /// In en, this message translates to:
+ /// **'Income'**
+ String get cashFlowIncome;
+
+ /// Summary label and segment label for expenses.
+ ///
+ /// In en, this message translates to:
+ /// **'Expenses'**
+ String get cashFlowExpenses;
+
+ /// Summary label for income minus expenses.
+ ///
+ /// In en, this message translates to:
+ /// **'Net savings'**
+ String get cashFlowNetSavings;
+
+ /// Savings rate shown under net savings, e.g. '18.2% savings rate'.
+ ///
+ /// In en, this message translates to:
+ /// **'{rate} savings rate'**
+ String cashFlowSavingsRate(String rate);
+
+ /// Section header for the expense category chart and list.
+ ///
+ /// In en, this message translates to:
+ /// **'Expenses by category'**
+ String get cashFlowExpensesByCategory;
+
+ /// Section header for the income category chart and list.
+ ///
+ /// In en, this message translates to:
+ /// **'Income by category'**
+ String get cashFlowIncomeByCategory;
+
+ /// Category row subtitle with its share of total expenses.
+ ///
+ /// In en, this message translates to:
+ /// **'{percent} of expenses'**
+ String cashFlowShareOfExpenses(String percent);
+
+ /// Category row subtitle with its share of total income.
+ ///
+ /// In en, this message translates to:
+ /// **'{percent} of income'**
+ String cashFlowShareOfIncome(String percent);
+
+ /// Empty state title when the period has no categorized cash flow.
+ ///
+ /// In en, this message translates to:
+ /// **'No income or expenses in this period'**
+ String get cashFlowEmpty;
+
+ /// Empty state subtitle on the Cash Flow screen.
+ ///
+ /// In en, this message translates to:
+ /// **'Try another period or pull to refresh.'**
+ String get cashFlowEmptySubtitle;
+
+ /// Shown in the category section when the expense side is empty.
+ ///
+ /// In en, this message translates to:
+ /// **'No expenses in this period'**
+ String get cashFlowNoExpenses;
+
+ /// Shown in the category section when the income side is empty.
+ ///
+ /// In en, this message translates to:
+ /// **'No income in this period'**
+ String get cashFlowNoIncome;
+
+ /// Error state title when the cash flow request fails.
+ ///
+ /// In en, this message translates to:
+ /// **'Couldn\'t load cash flow'**
+ String get cashFlowLoadFailed;
+
+ /// Error state message when the device is offline and no report is loaded.
+ ///
+ /// In en, this message translates to:
+ /// **'You\'re offline. Cash flow is calculated by your Sure server, so it needs a connection.'**
+ String get cashFlowOffline;
+
+ /// Badge shown when the displayed report could not be refreshed.
+ ///
+ /// In en, this message translates to:
+ /// **'Outdated'**
+ String get cashFlowOutdated;
+
+ /// Empty state of the category transactions screen.
+ ///
+ /// In en, this message translates to:
+ /// **'No transactions in this period'**
+ String get cashFlowTransactionsEmpty;
+
+ /// Error state of the category transactions screen.
+ ///
+ /// In en, this message translates to:
+ /// **'Couldn\'t load transactions'**
+ String get cashFlowTransactionsLoadFailed;
}
class _AppLocalizationsDelegate
diff --git a/mobile/lib/l10n/app_localizations_en.dart b/mobile/lib/l10n/app_localizations_en.dart
index 335b255add..fcfa4c938d 100644
--- a/mobile/lib/l10n/app_localizations_en.dart
+++ b/mobile/lib/l10n/app_localizations_en.dart
@@ -1158,4 +1158,89 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get budgetCategoryTransactionsLoadFailed =>
'Couldn\'t load transactions';
+
+ @override
+ String get moreCashFlow => 'Cash Flow';
+
+ @override
+ String get moreCashFlowSubtitle => 'Income, spending and savings by category';
+
+ @override
+ String get cashFlowTitle => 'Cash Flow';
+
+ @override
+ String get cashFlowPeriodCurrentMonth => 'This month';
+
+ @override
+ String get cashFlowPeriodLastMonth => 'Last month';
+
+ @override
+ String get cashFlowPeriodLast30Days => 'Last 30 days';
+
+ @override
+ String get cashFlowPeriodLast90Days => 'Last 90 days';
+
+ @override
+ String get cashFlowPeriodCurrentYear => 'Year to date';
+
+ @override
+ String get cashFlowPeriodLast365Days => 'Last 365 days';
+
+ @override
+ String get cashFlowIncome => 'Income';
+
+ @override
+ String get cashFlowExpenses => 'Expenses';
+
+ @override
+ String get cashFlowNetSavings => 'Net savings';
+
+ @override
+ String cashFlowSavingsRate(String rate) {
+ return '$rate savings rate';
+ }
+
+ @override
+ String get cashFlowExpensesByCategory => 'Expenses by category';
+
+ @override
+ String get cashFlowIncomeByCategory => 'Income by category';
+
+ @override
+ String cashFlowShareOfExpenses(String percent) {
+ return '$percent of expenses';
+ }
+
+ @override
+ String cashFlowShareOfIncome(String percent) {
+ return '$percent of income';
+ }
+
+ @override
+ String get cashFlowEmpty => 'No income or expenses in this period';
+
+ @override
+ String get cashFlowEmptySubtitle => 'Try another period or pull to refresh.';
+
+ @override
+ String get cashFlowNoExpenses => 'No expenses in this period';
+
+ @override
+ String get cashFlowNoIncome => 'No income in this period';
+
+ @override
+ String get cashFlowLoadFailed => 'Couldn\'t load cash flow';
+
+ @override
+ String get cashFlowOffline =>
+ 'You\'re offline. Cash flow is calculated by your Sure server, so it needs a connection.';
+
+ @override
+ String get cashFlowOutdated => 'Outdated';
+
+ @override
+ String get cashFlowTransactionsEmpty => 'No transactions in this period';
+
+ @override
+ String get cashFlowTransactionsLoadFailed => 'Couldn\'t load transactions';
}
diff --git a/mobile/lib/l10n/app_localizations_sv.dart b/mobile/lib/l10n/app_localizations_sv.dart
index bf1f703ff0..5bd2667ee8 100644
--- a/mobile/lib/l10n/app_localizations_sv.dart
+++ b/mobile/lib/l10n/app_localizations_sv.dart
@@ -1169,4 +1169,92 @@ class AppLocalizationsSv extends AppLocalizations {
@override
String get budgetCategoryTransactionsLoadFailed =>
'Kunde inte läsa in transaktioner';
+
+ @override
+ String get moreCashFlow => 'Kassaflöde';
+
+ @override
+ String get moreCashFlowSubtitle =>
+ 'Inkomster, utgifter och sparande per kategori';
+
+ @override
+ String get cashFlowTitle => 'Kassaflöde';
+
+ @override
+ String get cashFlowPeriodCurrentMonth => 'Den här månaden';
+
+ @override
+ String get cashFlowPeriodLastMonth => 'Förra månaden';
+
+ @override
+ String get cashFlowPeriodLast30Days => 'Senaste 30 dagarna';
+
+ @override
+ String get cashFlowPeriodLast90Days => 'Senaste 90 dagarna';
+
+ @override
+ String get cashFlowPeriodCurrentYear => 'Hittills i år';
+
+ @override
+ String get cashFlowPeriodLast365Days => 'Senaste 365 dagarna';
+
+ @override
+ String get cashFlowIncome => 'Inkomster';
+
+ @override
+ String get cashFlowExpenses => 'Utgifter';
+
+ @override
+ String get cashFlowNetSavings => 'Nettosparande';
+
+ @override
+ String cashFlowSavingsRate(String rate) {
+ return 'Sparkvot: $rate';
+ }
+
+ @override
+ String get cashFlowExpensesByCategory => 'Utgifter per kategori';
+
+ @override
+ String get cashFlowIncomeByCategory => 'Inkomster per kategori';
+
+ @override
+ String cashFlowShareOfExpenses(String percent) {
+ return '$percent av utgifterna';
+ }
+
+ @override
+ String cashFlowShareOfIncome(String percent) {
+ return '$percent av inkomsterna';
+ }
+
+ @override
+ String get cashFlowEmpty => 'Inga inkomster eller utgifter under perioden';
+
+ @override
+ String get cashFlowEmptySubtitle =>
+ 'Prova en annan period eller dra för att uppdatera.';
+
+ @override
+ String get cashFlowNoExpenses => 'Inga utgifter under perioden';
+
+ @override
+ String get cashFlowNoIncome => 'Inga inkomster under perioden';
+
+ @override
+ String get cashFlowLoadFailed => 'Kunde inte läsa in kassaflödet';
+
+ @override
+ String get cashFlowOffline =>
+ 'Du är offline. Kassaflödet beräknas av din Sure-server och kräver en anslutning.';
+
+ @override
+ String get cashFlowOutdated => 'Inaktuell';
+
+ @override
+ String get cashFlowTransactionsEmpty => 'Inga transaktioner under perioden';
+
+ @override
+ String get cashFlowTransactionsLoadFailed =>
+ 'Kunde inte läsa in transaktioner';
}
diff --git a/mobile/lib/l10n/app_sv.arb b/mobile/lib/l10n/app_sv.arb
index c601b46d93..28f7ea451b 100644
--- a/mobile/lib/l10n/app_sv.arb
+++ b/mobile/lib/l10n/app_sv.arb
@@ -303,6 +303,7 @@
"chatListHoursAgo": "för {hours} tim sedan",
"chatListDaysAgo": "för {days} d sedan",
"chatConversationStartFailed": "Det gick inte att starta konversationen. Försök igen.",
+
"moreBudgets": "Budgetar",
"moreBudgetsSubtitle": "Budgeterat mot faktiskt utfall per kategori",
"budgetsTitle": "Budgetar",
@@ -336,5 +337,32 @@
"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"
+ "budgetCategoryTransactionsLoadFailed": "Kunde inte läsa in transaktioner",
+
+"moreCashFlow": "Kassaflöde",
+ "moreCashFlowSubtitle": "Inkomster, utgifter och sparande per kategori",
+ "cashFlowTitle": "Kassaflöde",
+ "cashFlowPeriodCurrentMonth": "Den här månaden",
+ "cashFlowPeriodLastMonth": "Förra månaden",
+ "cashFlowPeriodLast30Days": "Senaste 30 dagarna",
+ "cashFlowPeriodLast90Days": "Senaste 90 dagarna",
+ "cashFlowPeriodCurrentYear": "Hittills i år",
+ "cashFlowPeriodLast365Days": "Senaste 365 dagarna",
+ "cashFlowIncome": "Inkomster",
+ "cashFlowExpenses": "Utgifter",
+ "cashFlowNetSavings": "Nettosparande",
+ "cashFlowSavingsRate": "Sparkvot: {rate}",
+ "cashFlowExpensesByCategory": "Utgifter per kategori",
+ "cashFlowIncomeByCategory": "Inkomster per kategori",
+ "cashFlowShareOfExpenses": "{percent} av utgifterna",
+ "cashFlowShareOfIncome": "{percent} av inkomsterna",
+ "cashFlowEmpty": "Inga inkomster eller utgifter under perioden",
+ "cashFlowEmptySubtitle": "Prova en annan period eller dra för att uppdatera.",
+ "cashFlowNoExpenses": "Inga utgifter under perioden",
+ "cashFlowNoIncome": "Inga inkomster under perioden",
+ "cashFlowLoadFailed": "Kunde inte läsa in kassaflödet",
+ "cashFlowOffline": "Du är offline. Kassaflödet beräknas av din Sure-server och kräver en anslutning.",
+ "cashFlowOutdated": "Inaktuell",
+ "cashFlowTransactionsEmpty": "Inga transaktioner under perioden",
+ "cashFlowTransactionsLoadFailed": "Kunde inte läsa in transaktioner"
}
diff --git a/mobile/lib/models/cash_flow.dart b/mobile/lib/models/cash_flow.dart
new file mode 100644
index 0000000000..6bba5cdb8a
--- /dev/null
+++ b/mobile/lib/models/cash_flow.dart
@@ -0,0 +1,337 @@
+/// Cash flow report models backed by `GET /api/v1/cash_flow?view=sankey`.
+///
+/// The server does all the aggregation (refund netting, parent/subcategory
+/// partitioning, transfer exclusion); the client only reshapes the Sankey
+/// graph into per-side category lists for the summary, chart and ranked list.
+library;
+
+/// Report periods offered by the mobile cash flow screen. They mirror the web
+/// `Period` presets (`app/models/period.rb`) so the same label covers the same
+/// date range on both clients.
+enum CashFlowPeriod {
+ currentMonth,
+ lastMonth,
+ last30Days,
+ last90Days,
+ currentYear,
+ last365Days;
+
+ /// Inclusive date range for this period relative to [today] (date part only).
+ ///
+ /// [monthStartDay] is the family's month start (`Family#month_start_day`,
+ /// 1..28). Like the web's `Period.current_month_for` / `last_month_for`, it
+ /// moves "This month" and "Last month" to the custom boundaries; the other
+ /// presets are rolling or calendar-year ranges and ignore it.
+ CashFlowDateRange rangeFor(DateTime today, {int monthStartDay = 1}) {
+ final day = DateTime(today.year, today.month, today.day);
+ switch (this) {
+ case CashFlowPeriod.currentMonth:
+ if (monthStartDay > 1) {
+ // Family#current_custom_month_period: start to its end, which can
+ // run past today (the web shows the whole custom month).
+ final start = _customMonthStart(day, monthStartDay);
+ return CashFlowDateRange(start, _customMonthEnd(start));
+ }
+ return CashFlowDateRange(DateTime(day.year, day.month, 1), day);
+ case CashFlowPeriod.lastMonth:
+ if (monthStartDay > 1) {
+ final currentStart = _customMonthStart(day, monthStartDay);
+ final previousDay = DateTime(
+ currentStart.year,
+ currentStart.month,
+ currentStart.day - 1,
+ );
+ final start = _customMonthStart(previousDay, monthStartDay);
+ return CashFlowDateRange(start, _customMonthEnd(start));
+ }
+ // Day 0 of the current month is the last day of the previous month.
+ return CashFlowDateRange(
+ DateTime(day.year, day.month - 1, 1),
+ DateTime(day.year, day.month, 0),
+ );
+ case CashFlowPeriod.last30Days:
+ return CashFlowDateRange(_daysBefore(day, 30), day);
+ case CashFlowPeriod.last90Days:
+ return CashFlowDateRange(_daysBefore(day, 90), day);
+ case CashFlowPeriod.currentYear:
+ return CashFlowDateRange(DateTime(day.year, 1, 1), day);
+ case CashFlowPeriod.last365Days:
+ return CashFlowDateRange(_daysBefore(day, 365), day);
+ }
+ }
+
+ /// `Family#custom_month_start_for`.
+ static DateTime _customMonthStart(DateTime day, int monthStartDay) =>
+ day.day >= monthStartDay
+ ? DateTime(day.year, day.month, monthStartDay)
+ : DateTime(day.year, day.month - 1, monthStartDay);
+
+ /// `Family#custom_month_end_for`: the day before the next month's start.
+ static DateTime _customMonthEnd(DateTime start) =>
+ DateTime(start.year, start.month + 1, start.day - 1);
+
+ // Calendar arithmetic (not Duration) so DST transitions never shift the day.
+ static DateTime _daysBefore(DateTime day, int days) =>
+ DateTime(day.year, day.month, day.day - days);
+}
+
+/// Inclusive start/end dates of a report.
+class CashFlowDateRange {
+ const CashFlowDateRange(this.start, this.end);
+
+ final DateTime start;
+ final DateTime end;
+
+ String get startIso => isoDate(start);
+ String get endIso => isoDate(end);
+
+ /// `YYYY-MM-DD`, the format the Sure API expects for dates.
+ static String isoDate(DateTime date) {
+ String two(int v) => v.toString().padLeft(2, '0');
+ return '${date.year.toString().padLeft(4, '0')}-${two(date.month)}-${two(date.day)}';
+ }
+
+ @override
+ bool operator ==(Object other) =>
+ other is CashFlowDateRange && other.start == start && other.end == end;
+
+ @override
+ int get hashCode => Object.hash(start, end);
+}
+
+/// Which side of the cash flow a category belongs to.
+enum CashFlowSide { income, expense }
+
+/// One category on one side of the report (a root category; subcategories are
+/// folded into [children]).
+class CashFlowCategory {
+ const CashFlowCategory({
+ required this.id,
+ required this.name,
+ required this.side,
+ required this.amount,
+ required this.percentage,
+ this.categoryId,
+ this.color,
+ this.children = const [],
+ this.relatedSubcategoryIds = const [],
+ });
+
+ /// Stable node id from the API (e.g. `expense_<key>`).
+ final String id;
+ final String name;
+ final CashFlowSide side;
+
+ /// Nonnegative amount in the report currency.
+ final double amount;
+
+ /// Share of the side total, in percentage points (0–100), as computed by
+ /// the server.
+ final double percentage;
+
+ /// Sure category id; `null` for synthetic buckets such as Uncategorized,
+ /// which the transactions API cannot filter on.
+ final String? categoryId;
+
+ /// User category color (`#rrggbb`), when the category has one.
+ final String? color;
+
+ /// Subcategories with a nonzero amount on this side.
+ final List<CashFlowCategory> children;
+
+ /// Ids of this category's subcategories that the report lists on the other
+ /// side only. The server partitions each category's net amount by
+ /// direction, so a subcategory whose refunds outweigh its spending appears
+ /// under the income counterpart of an expense category (and vice versa).
+ final List<String> relatedSubcategoryIds;
+
+ /// Category ids to request when drilling into this category's
+ /// transactions: the category itself plus every subcategory the report
+ /// knows on either side, like the web's category filter, which includes
+ /// all subcategories of a parent.
+ List<String> get transactionCategoryIds => {
+ if (categoryId != null) categoryId!,
+ for (final child in children)
+ if (child.categoryId != null) child.categoryId!,
+ ...relatedSubcategoryIds,
+ }.toList(growable: false);
+
+ CashFlowCategory _withRelatedSubcategoryIds(List<String> ids) =>
+ CashFlowCategory(
+ id: id,
+ name: name,
+ side: side,
+ amount: amount,
+ percentage: percentage,
+ categoryId: categoryId,
+ color: color,
+ children: children,
+ relatedSubcategoryIds: ids,
+ );
+
+ bool get canDrillDown => categoryId != null;
+}
+
+/// A cash flow report for one period.
+class CashFlowReport {
+ const CashFlowReport({
+ required this.currency,
+ required this.startDate,
+ required this.endDate,
+ required this.income,
+ required this.spending,
+ required this.netSavings,
+ required this.incomeCategories,
+ required this.expenseCategories,
+ });
+
+ final String currency;
+ final DateTime startDate;
+ final DateTime endDate;
+ final double income;
+ final double spending;
+ final double netSavings;
+
+ /// Income categories, largest first.
+ final List<CashFlowCategory> incomeCategories;
+
+ /// Expense categories, largest first.
+ final List<CashFlowCategory> expenseCategories;
+
+ /// Net savings as a percentage of income; `null` when income is not
+ /// positive (matches the API's `savings_rate` semantics).
+ double? get savingsRate => income > 0 ? netSavings / income * 100 : null;
+
+ List<CashFlowCategory> categoriesFor(CashFlowSide side) =>
+ side == CashFlowSide.income ? incomeCategories : expenseCategories;
+
+ double totalFor(CashFlowSide side) =>
+ side == CashFlowSide.income ? income : spending;
+
+ bool get isEmpty => incomeCategories.isEmpty && expenseCategories.isEmpty;
+
+ /// Parses the `view=sankey` envelope:
+ /// `{currency, period: {start_date, end_date}, sankey: {income, spending,
+ /// net_savings, nodes, links}}`.
+ factory CashFlowReport.fromJson(Map<String, dynamic> json) {
+ final period = _map(json['period']);
+ final sankey = _map(json['sankey']);
+ final nodes = (sankey['nodes'] as List? ?? const [])
+ .map((n) => _map(n))
+ .toList(growable: false);
+ final links = (sankey['links'] as List? ?? const [])
+ .map((l) => _map(l))
+ .toList(growable: false);
+
+ final centerIndexes = <int>{
+ for (var i = 0; i < nodes.length; i++)
+ if (nodes[i]['kind'] == 'cash_flow' || nodes[i]['kind'] == 'account') i,
+ };
+
+ // Root categories are linked directly to a center node; subcategories
+ // hang off a root (expense: root -> sub, income: sub -> root).
+ final incomeRoots = <int>[];
+ final expenseRoots = <int>[];
+ final childrenOf = <int, List<int>>{};
+ for (final link in links) {
+ final source = _int(link['source']);
+ final target = _int(link['target']);
+ if (source == null || target == null) continue;
+ if (source >= nodes.length || target >= nodes.length) continue;
+ final sourceKind = nodes[source]['kind'];
+ final targetKind = nodes[target]['kind'];
+
+ if (centerIndexes.contains(target) && sourceKind == 'income') {
+ if (!incomeRoots.contains(source)) incomeRoots.add(source);
+ } else if (centerIndexes.contains(source) && targetKind == 'expense') {
+ if (!expenseRoots.contains(target)) expenseRoots.add(target);
+ } else if (sourceKind == 'expense' && targetKind == 'expense') {
+ childrenOf.putIfAbsent(source, () => []).add(target);
+ } else if (sourceKind == 'income' && targetKind == 'income') {
+ childrenOf.putIfAbsent(target, () => []).add(source);
+ }
+ }
+
+ CashFlowCategory build(int index, CashFlowSide side) {
+ final node = nodes[index];
+ final children = (childrenOf[index] ?? const <int>[])
+ .map((c) => build(c, side))
+ // The server only sends positive side amounts; anything else
+ // could not be drawn in the chart, so it is not listed either.
+ .where((c) => c.amount > 0)
+ .toList()
+ ..sort((a, b) => b.amount.compareTo(a.amount));
+ return CashFlowCategory(
+ id: node['id']?.toString() ?? '$index',
+ name: node['name']?.toString() ?? '',
+ side: side,
+ amount: _double(node['value']),
+ percentage: _double(node['percentage']),
+ categoryId: _nonEmpty(node['category_id']),
+ color: _nonEmpty(node['color']),
+ children: children,
+ );
+ }
+
+ List<CashFlowCategory> side(List<int> roots, CashFlowSide s) =>
+ roots.map((i) => build(i, s)).where((c) => c.amount > 0).toList()
+ ..sort((a, b) => b.amount.compareTo(a.amount));
+
+ final incomeCategories = side(incomeRoots, CashFlowSide.income);
+ final expenseCategories = side(expenseRoots, CashFlowSide.expense);
+
+ // Subcategory ids per root category id, across both sides.
+ final subcategoryIds = <String, Set<String>>{};
+ for (final root in [...incomeCategories, ...expenseCategories]) {
+ final rootId = root.categoryId;
+ if (rootId == null) continue;
+ final ids = subcategoryIds.putIfAbsent(rootId, () => <String>{});
+ for (final child in root.children) {
+ if (child.categoryId != null) ids.add(child.categoryId!);
+ }
+ }
+ List<CashFlowCategory> withRelated(List<CashFlowCategory> roots) => [
+ for (final root in roots)
+ if (root.categoryId == null)
+ root
+ else
+ root._withRelatedSubcategoryIds(
+ subcategoryIds[root.categoryId]!.difference({
+ for (final child in root.children) child.categoryId,
+ }).toList(growable: false),
+ ),
+ ];
+
+ return CashFlowReport(
+ currency: json['currency']?.toString() ?? '',
+ startDate: _date(period['start_date']),
+ endDate: _date(period['end_date']),
+ income: _double(sankey['income']),
+ spending: _double(sankey['spending']),
+ netSavings: _double(sankey['net_savings']),
+ incomeCategories: withRelated(incomeCategories),
+ expenseCategories: withRelated(expenseCategories),
+ );
+ }
+
+ static Map<String, dynamic> _map(Object? value) =>
+ value is Map ? Map<String, dynamic>.from(value) : <String, dynamic>{};
+
+ static double _double(Object? value) {
+ if (value is num) return value.toDouble();
+ return double.tryParse(value?.toString() ?? '') ?? 0;
+ }
+
+ static int? _int(Object? value) {
+ if (value is int) return value;
+ return int.tryParse(value?.toString() ?? '');
+ }
+
+ static String? _nonEmpty(Object? value) {
+ final text = value?.toString();
+ return text == null || text.isEmpty ? null : text;
+ }
+
+ static DateTime _date(Object? value) =>
+ DateTime.tryParse(value?.toString() ?? '') ?? DateTime(1970);
+}
diff --git a/mobile/lib/models/transaction.dart b/mobile/lib/models/transaction.dart
index d6e0b6a12c..e3e0cd776f 100644
--- a/mobile/lib/models/transaction.dart
+++ b/mobile/lib/models/transaction.dart
@@ -17,6 +17,24 @@ class Transaction {
final List<String> tagNames;
final bool tagsProvided;
+ /// The stored amount, unrounded, as a plain decimal string in the API's
+ /// sign convention (positive = outflow, negative = inflow). Null when the
+ /// server predates the field.
+ final String? amountDecimal;
+
+ /// The transaction kind (`standard`, `loan_payment`,
+ /// `investment_contribution`, `funds_movement`, ...). Null when the server
+ /// predates the field.
+ final String? kind;
+
+ /// Whether the entry is left out of budgets and reports. Splitting marks
+ /// the parent excluded. Null when the server predates the field.
+ final bool? excluded;
+
+ /// Whether the entry has split children. Null when the server predates the
+ /// field.
+ final bool? splitParent;
+
Transaction({
this.id,
required this.accountId,
@@ -35,6 +53,10 @@ class Transaction {
List<String> tagIds = const [],
List<String> tagNames = const [],
bool? tagsProvided,
+ this.amountDecimal,
+ this.kind,
+ this.excluded,
+ this.splitParent,
}) : tagIds = List.unmodifiable(tagIds),
tagNames = List.unmodifiable(tagNames),
categoryProvided =
@@ -142,9 +164,20 @@ class Transaction {
tagIds: tagIds,
tagNames: tagNames,
tagsProvided: tagsProvided,
+ amountDecimal: _nonEmptyString(json['amount_decimal']),
+ kind: _nonEmptyString(json['kind']),
+ excluded: json['excluded'] is bool ? json['excluded'] as bool : null,
+ splitParent:
+ json['split_parent'] is bool ? json['split_parent'] as bool : null,
);
}
+ static String? _nonEmptyString(Object? value) {
+ if (value == null) return null;
+ final text = value.toString().trim();
+ return text.isEmpty ? null : text;
+ }
+
Map<String, dynamic> toJson() {
return {
if (id != null) 'id': id,
diff --git a/mobile/lib/screens/cash_flow_category_transactions_screen.dart b/mobile/lib/screens/cash_flow_category_transactions_screen.dart
new file mode 100644
index 0000000000..a2143a5dda
--- /dev/null
+++ b/mobile/lib/screens/cash_flow_category_transactions_screen.dart
@@ -0,0 +1,399 @@
+import 'package:flutter/material.dart';
+import 'package:intl/intl.dart';
+import 'package:provider/provider.dart';
+
+import '../l10n/app_localizations.dart';
+import '../models/cash_flow.dart';
+import '../models/category.dart';
+import '../models/transaction.dart';
+import '../providers/auth_provider.dart';
+import '../providers/privacy_provider.dart';
+import '../services/categories_service.dart';
+import '../services/transactions_service.dart';
+import '../theme/sure_colors.dart';
+import '../theme/sure_spacing.dart';
+import '../theme/sure_tokens.dart';
+import '../utils/amount_parser.dart';
+import '../utils/money_masker.dart';
+import '../widgets/money_text.dart';
+import '../widgets/sure_button.dart';
+import '../widgets/sure_icon.dart';
+import '../widgets/sure_list_group.dart';
+import 'cash_flow_screen.dart' show AccessTokenLoader;
+
+/// Kinds the income statement leaves out of income and spending
+/// (`Transaction::BUDGET_EXCLUDED_KINDS`).
+const Set<String> cashFlowExcludedKinds = {
+ 'funds_movement',
+ 'one_time',
+ 'cc_payment',
+};
+
+/// Whether [transaction] counts in the cash flow report, as far as the
+/// transactions index says. Fields an older server leaves out don't filter.
+@visibleForTesting
+bool countsInCashFlow(Transaction transaction) {
+ if (transaction.excluded == true) return false;
+ if (transaction.splitParent == true) return false;
+ final kind = transaction.kind;
+ return kind == null || !cashFlowExcludedKinds.contains(kind);
+}
+
+/// Whether the report counts [transaction] as income. Loan payments and
+/// investment contributions are outflows whatever their sign
+/// (`IncomeStatement::ScopedTransactionsQuery#classification_sql`); other
+/// rows follow the amount's sign, so a refund still shows as money in.
+@visibleForTesting
+bool isCashFlowIncome(Transaction transaction) {
+ switch (transaction.kind) {
+ case 'loan_payment':
+ case 'investment_contribution':
+ return false;
+ }
+ return transaction.isIncome;
+}
+
+/// Transactions in one cash flow category (and its subcategories) for the
+/// report period, fetched page by page from `GET /api/v1/transactions` with
+/// `start_date`, `end_date` and `category_ids[]`. Refunds are included, since
+/// the cash flow report nets them within the category.
+///
+/// Like the web's category filter, every subcategory is included, also one
+/// the report leaves out because its refunds net it to zero. Its ids come
+/// from `GET /api/v1/categories?parent_id=…`; if that lookup fails, the
+/// subcategories named in the report are used.
+///
+/// Rows the report doesn't count are left out, using the index's `excluded`,
+/// `split_parent` and `kind` fields: excluded entries, split parents (their
+/// children carry the amount) and transfer-like kinds. Loan payments and
+/// investment contributions are shown as outflows whatever their sign, as
+/// the report counts them. Servers without these fields show every row.
+class CashFlowCategoryTransactionsScreen extends StatefulWidget {
+ const CashFlowCategoryTransactionsScreen({
+ super.key,
+ required this.category,
+ required this.range,
+ this.service,
+ this.categoriesService,
+ this.accessTokenLoader,
+ this.onUnauthorized,
+ });
+
+ final CashFlowCategory category;
+
+ /// Called on a 401; defaults to [AuthProvider.logout].
+ final Future<void> Function(BuildContext context)? onUnauthorized;
+ final CashFlowDateRange range;
+ final TransactionsService? service;
+ final CategoriesService? categoriesService;
+ final AccessTokenLoader? accessTokenLoader;
+
+ @override
+ State<CashFlowCategoryTransactionsScreen> createState() =>
+ _CashFlowCategoryTransactionsScreenState();
+}
+
+class _CashFlowCategoryTransactionsScreenState
+ extends State<CashFlowCategoryTransactionsScreen> {
+ static const int _perPage = 50;
+
+ late final TransactionsService _service =
+ widget.service ?? TransactionsService();
+ late final CategoriesService _categoriesService =
+ widget.categoriesService ?? CategoriesService();
+ final ScrollController _scroll = ScrollController();
+ final List<Transaction> _transactions = [];
+
+ /// The category plus all of its subcategories, once the lookup succeeded.
+ List<String>? _categoryIds;
+ int _page = 0;
+ int? _totalPages;
+ bool _loading = false;
+ bool _failed = false;
+
+ /// Bumped by [_refresh]; a page response from an older generation is
+ /// dropped so it can't land in the reset list.
+ int _generation = 0;
+
+ bool get _hasMore => _totalPages == null || _page < _totalPages!;
+
+ /// Pages in a row that had no row to show; capped so a long run of
+ /// filtered-out rows doesn't fetch every page at once.
+ int _emptyPagesInARow = 0;
+ static const int _maxEmptyPagesInARow = 3;
+
+ @override
+ void initState() {
+ super.initState();
+ _scroll.addListener(() {
+ if (_scroll.position.extentAfter < 400) _loadMore();
+ });
+ WidgetsBinding.instance.addPostFrameCallback((_) => _loadMore());
+ }
+
+ @override
+ void dispose() {
+ _scroll.dispose();
+ super.dispose();
+ }
+
+ Future<String?> _accessToken() {
+ final loader = widget.accessTokenLoader;
+ if (loader != null) return loader(context);
+ return context.read<AuthProvider>().getValidAccessToken();
+ }
+
+ @visibleForTesting
+ Future<void> refreshForTest() => _refresh();
+
+ @visibleForTesting
+ Future<void> loadMoreForTest() => _loadMore();
+
+ Future<void> _refresh() async {
+ setState(() {
+ _generation++;
+ _transactions.clear();
+ _page = 0;
+ _totalPages = null;
+ _failed = false;
+ _loading = false;
+ _emptyPagesInARow = 0;
+ });
+ await _loadMore();
+ }
+
+ Future<void> _loadMore() async {
+ if (_loading || !_hasMore || _failed) return;
+ final generation = _generation;
+ final nextPage = _page + 1;
+ setState(() => _loading = true);
+
+ Map<String, dynamic>? result;
+ var unauthorized = false;
+ try {
+ final token = await _accessToken();
+ if (token != null) {
+ final categoryIds = _categoryIds ?? await _lookUpCategoryIds(token);
+ if (categoryIds == null) {
+ unauthorized = true;
+ } else {
+ result = await _service.getTransactions(
+ accessToken: token,
+ page: nextPage,
+ perPage: _perPage,
+ startDate: widget.range.startIso,
+ endDate: widget.range.endIso,
+ categoryIds: categoryIds,
+ );
+ unauthorized = result['error'] == 'unauthorized';
+ }
+ }
+ } catch (_) {
+ // A failed token refresh (or storage error) is a failed page.
+ result = null;
+ }
+ if (!mounted || generation != _generation) return;
+
+ var shown = 0;
+ setState(() {
+ _loading = false;
+ if (result != null && result['success'] == true) {
+ final page = (result['transactions'] as List)
+ .cast<Transaction>()
+ .where(countsInCashFlow)
+ .toList();
+ shown = page.length;
+ _transactions.addAll(page);
+ _page = nextPage;
+ // GET /api/v1/transactions always returns pagination.total_pages.
+ final pagination = result['pagination'];
+ if (pagination is Map && pagination['total_pages'] is int) {
+ _totalPages = pagination['total_pages'] as int;
+ }
+ } else {
+ _failed = true;
+ }
+ });
+ if (unauthorized) {
+ await _handleUnauthorized();
+ return;
+ }
+ // A page whose rows were all filtered out leaves nothing to scroll, so
+ // fetch the next one (a few at most per scroll).
+ if (result != null && result['success'] == true) {
+ _emptyPagesInARow = shown == 0 ? _emptyPagesInARow + 1 : 0;
+ if (shown == 0 &&
+ _hasMore &&
+ _emptyPagesInARow < _maxEmptyPagesInARow) {
+ await _loadMore();
+ }
+ }
+ }
+
+ /// The category's id plus all of its subcategory ids. Falls back to the
+ /// ids the report knows when the lookup fails, and returns `null` on 401.
+ Future<List<String>?> _lookUpCategoryIds(String token) async {
+ final known = widget.category.transactionCategoryIds;
+ final rootId = widget.category.categoryId;
+ if (rootId == null) return known;
+ Map<String, dynamic> lookup;
+ try {
+ lookup = await _categoriesService.getCategories(
+ accessToken: token,
+ parentId: rootId,
+ perPage: 100,
+ );
+ } catch (_) {
+ return known;
+ }
+ if (lookup['error'] == 'unauthorized') return null;
+ if (lookup['success'] != true) return known;
+ final ids = {
+ ...known,
+ for (final category in (lookup['categories'] as List).cast<Category>())
+ if (category.id.isNotEmpty) category.id,
+ }.toList(growable: false);
+ if (mounted) _categoryIds = ids;
+ return ids;
+ }
+
+ Future<void> _handleUnauthorized() async {
+ final handler = widget.onUnauthorized;
+ if (handler != null) return handler(context);
+ try {
+ await context.read<AuthProvider>().logout();
+ } on ProviderNotFoundException {
+ // No auth provider above this screen (e.g. in isolation).
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final l = AppLocalizations.of(context);
+ final palette = SureColors.of(context).palette;
+ final theme = Theme.of(context);
+ final hidden = context.watch<PrivacyProvider>().hidden;
+ final locale = Localizations.localeOf(context).toString();
+ final dates = DateFormat.yMMMd(locale);
+
+ Widget body;
+ if (_transactions.isEmpty && _loading) {
+ body = const Center(child: CircularProgressIndicator());
+ } else if (_transactions.isEmpty) {
+ body = ListView(
+ physics: const AlwaysScrollableScrollPhysics(),
+ padding: const EdgeInsets.all(SureSpacing.xxxl),
+ children: [
+ const SizedBox(height: SureSpacing.huge),
+ SureIcon(
+ _failed ? SureIcons.circleAlert : SureIcons.receipt,
+ size: SureIconSize.xxl,
+ color: palette.textSubdued,
+ ),
+ const SizedBox(height: SureSpacing.lg),
+ Text(
+ _failed
+ ? l.cashFlowTransactionsLoadFailed
+ : l.cashFlowTransactionsEmpty,
+ textAlign: TextAlign.center,
+ style: theme.textTheme.titleMedium,
+ ),
+ if (_failed) ...[
+ const SizedBox(height: SureSpacing.xl),
+ Center(
+ child: SureButton(
+ label: l.commonTryAgain,
+ onPressed: _refresh,
+ leading: const SureIcon(SureIcons.refresh, size: 18),
+ ),
+ ),
+ ],
+ ],
+ );
+ } else {
+ body = ListView(
+ controller: _scroll,
+ physics: const AlwaysScrollableScrollPhysics(),
+ padding: const EdgeInsets.fromLTRB(
+ SureSpacing.xl,
+ SureSpacing.md,
+ SureSpacing.xl,
+ SureSpacing.huge,
+ ),
+ children: [
+ SureListGroup(
+ header:
+ '${dates.format(widget.range.start)} – ${dates.format(widget.range.end)}',
+ children: [
+ for (final transaction in _transactions)
+ SureListRow(
+ title: transaction.name,
+ subtitle: _subtitle(transaction, dates),
+ trailing: _amount(context, transaction, hidden),
+ ),
+ ],
+ ),
+ if (_loading)
+ const Padding(
+ padding: EdgeInsets.all(SureSpacing.xl),
+ child: Center(child: CircularProgressIndicator()),
+ ),
+ if (_failed)
+ Padding(
+ padding: const EdgeInsets.all(SureSpacing.xl),
+ child: Center(
+ child: SureButton(
+ label: l.commonTryAgain,
+ variant: SureButtonVariant.outline,
+ onPressed: () {
+ setState(() => _failed = false);
+ _loadMore();
+ },
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+
+ return Scaffold(
+ appBar: AppBar(title: Text(widget.category.name)),
+ body: RefreshIndicator(onRefresh: _refresh, child: body),
+ );
+ }
+
+ String _subtitle(Transaction transaction, DateFormat dates) {
+ final date = DateTime.tryParse(transaction.date);
+ final parts = <String>[
+ date == null ? transaction.date : dates.format(date),
+ // Subcategory transactions show which subcategory they belong to.
+ if (transaction.categoryName != null &&
+ transaction.categoryName!.isNotEmpty &&
+ transaction.categoryName != widget.category.name)
+ transaction.categoryName!,
+ ];
+ return parts.join(' · ');
+ }
+
+ Widget _amount(BuildContext context, Transaction transaction, bool hidden) {
+ // The API's `amount` is a formatted string whose sign follows Sure's
+ // ledger convention; present it the way the report classifies it.
+ final isIncome = isCashFlowIncome(transaction);
+ // AmountParser's display text drops hyphen/en/em/figure dashes, minus
+ // signs and accounting parentheses.
+ String magnitude;
+ try {
+ magnitude = AmountParser.parse(transaction.amount).displayText;
+ } on FormatException {
+ magnitude = transaction.amount;
+ }
+ return MoneyText(
+ MoneyMasker.mask('${isIncome ? '+' : '-'}$magnitude', hidden: hidden),
+ trend: isIncome ? MoneyTrend.inflow : MoneyTrend.outflow,
+ style: Theme.of(context)
+ .textTheme
+ .titleSmall
+ ?.copyWith(fontWeight: SureTokens.weightMedium),
+ );
+ }
+}
diff --git a/mobile/lib/screens/cash_flow_screen.dart b/mobile/lib/screens/cash_flow_screen.dart
new file mode 100644
index 0000000000..8a8f95e841
--- /dev/null
+++ b/mobile/lib/screens/cash_flow_screen.dart
@@ -0,0 +1,771 @@
+import 'package:flutter/material.dart';
+import 'package:intl/intl.dart';
+import 'package:provider/provider.dart';
+
+import '../l10n/app_localizations.dart';
+import '../models/cash_flow.dart';
+import '../providers/auth_provider.dart';
+import '../providers/privacy_provider.dart';
+import '../services/cash_flow_service.dart';
+import '../services/categories_service.dart';
+import '../services/connectivity_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/cash_flow_donut_chart.dart';
+import '../widgets/money_text.dart';
+import '../widgets/sure_button.dart';
+import '../widgets/sure_card.dart';
+import '../widgets/sure_chip.dart';
+import '../widgets/sure_icon.dart';
+import '../widgets/sure_list_group.dart';
+import '../widgets/sure_segmented_control.dart';
+import 'cash_flow_category_transactions_screen.dart';
+
+/// Loads an access token. Defaults to [AuthProvider.getValidAccessToken];
+/// injectable so widget tests don't need the secure-storage backed provider.
+typedef AccessTokenLoader = Future<String?> Function(BuildContext context);
+
+/// Cash flow report: income vs expenses vs net savings for a period, plus
+/// expenses (or income) by category as a donut chart and a ranked list with
+/// each category's share. Tapping a category opens its transactions for the
+/// period. Mobile counterpart of the web dashboard's cash flow Sankey and
+/// outflows donut; all totals come from `GET /api/v1/cash_flow`.
+///
+/// The report is server-calculated, so it needs a connection. Reports already
+/// loaded in this screen stay visible (flagged "Outdated") when a refresh
+/// fails or the device goes offline, mirroring the net worth card.
+class CashFlowScreen extends StatefulWidget {
+ const CashFlowScreen({
+ super.key,
+ this.service,
+ this.transactionsService,
+ this.categoriesService,
+ this.accessTokenLoader,
+ this.clock,
+ this.initialPeriod = CashFlowPeriod.currentMonth,
+ this.onUnauthorized,
+ });
+
+ final CashFlowService? service;
+
+ /// Called when the server rejects the session (401). Defaults to
+ /// [AuthProvider.logout], like the dashboard and account screens, so the
+ /// app returns to login instead of retrying a revoked credential forever.
+ final Future<void> Function(BuildContext context)? onUnauthorized;
+
+ /// Passed to the category drill-down screen.
+ final TransactionsService? transactionsService;
+ final CategoriesService? categoriesService;
+ final AccessTokenLoader? accessTokenLoader;
+
+ /// Source of "today" for period ranges; injectable for tests.
+ final DateTime Function()? clock;
+ final CashFlowPeriod initialPeriod;
+
+ @override
+ State<CashFlowScreen> createState() => _CashFlowScreenState();
+}
+
+class _CashFlowScreenState extends State<CashFlowScreen> {
+ late final CashFlowService _service = widget.service ?? CashFlowService();
+
+ /// Family month start day once known (null until family settings load).
+ int? _monthStartDay;
+ late CashFlowPeriod _period = widget.initialPeriod;
+ CashFlowSide _side = CashFlowSide.expense;
+
+ final Map<CashFlowPeriod, CashFlowReport> _reports = {};
+
+ /// The date range each cached report was fetched for. A preset such as
+ /// "This month" moves when the date changes, so a cached report only
+ /// counts while its range still matches.
+ final Map<CashFlowPeriod, CashFlowDateRange> _reportRanges = {};
+ final Set<CashFlowPeriod> _stale = {};
+ bool _loading = false;
+ bool _offline = false;
+ bool _failed = false;
+ // Per period, so a response for one period is never dropped because the
+ // user switched to another while it was in flight.
+ final Map<CashFlowPeriod, int> _requestIds = {};
+
+ /// Requests in flight, with the date range each one asked for.
+ final Map<CashFlowPeriod, CashFlowDateRange> _inFlight = {};
+
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) => _load());
+ }
+
+ @override
+ void dispose() {
+ // Only closes a client the service created itself.
+ if (widget.service == null) _service.close();
+ super.dispose();
+ }
+
+ CashFlowDateRange _rangeFor(CashFlowPeriod period) => period.rangeFor(
+ (widget.clock ?? DateTime.now)(),
+ monthStartDay: _monthStartDay ?? 1,
+ );
+
+ /// The cached report for [period] when it is still for the current range,
+ /// or (flagged Outdated) when a refresh for the new range failed. While a
+ /// replacement is loading, an out-of-range report is not shown, so a
+ /// category tap can't open the old range.
+ CashFlowReport? _visibleReport(CashFlowPeriod period) {
+ final report = _reports[period];
+ if (report == null) return null;
+ if (_reportRanges[period] == _rangeFor(period) || _stale.contains(period)) {
+ return report;
+ }
+ return null;
+ }
+
+ Future<void> _handleUnauthorized() async {
+ final handler = widget.onUnauthorized;
+ if (handler != null) return handler(context);
+ try {
+ await context.read<AuthProvider>().logout();
+ } on ProviderNotFoundException {
+ // No auth provider above this screen (e.g. in isolation).
+ }
+ }
+
+ Future<String?> _accessToken() {
+ final loader = widget.accessTokenLoader;
+ if (loader != null) return loader(context);
+ return context.read<AuthProvider>().getValidAccessToken();
+ }
+
+ ConnectivityService? _connectivity() {
+ try {
+ return Provider.of<ConnectivityService>(context, listen: false);
+ } on ProviderNotFoundException {
+ return null;
+ }
+ }
+
+ Future<void> _load({bool force = false}) async {
+ final period = _period;
+ var range = _rangeFor(period);
+ if (!force &&
+ _reports.containsKey(period) &&
+ !_stale.contains(period) &&
+ _reportRanges[period] == range) {
+ return;
+ }
+ // Back on a period whose request is still running for the same range:
+ // wait for that one instead of starting (and discarding) another.
+ if (!force && _inFlight[period] == range) {
+ setState(() {
+ _loading = true;
+ _failed = false;
+ _offline = false;
+ });
+ return;
+ }
+ final requestId = (_requestIds[period] ?? 0) + 1;
+ _requestIds[period] = requestId;
+ _inFlight[period] = range;
+ setState(() {
+ _loading = true;
+ _failed = false;
+ _offline = false;
+ });
+
+ final offline = _connectivity()?.isOffline ?? false;
+ Map<String, dynamic>? result;
+ var unauthorized = false;
+ try {
+ final token = offline ? null : await _accessToken();
+ if (token != null) {
+ if (_monthStartDay == null) {
+ // "This month" / "Last month" follow the family's month start, as
+ // on the web. If settings can't load, calendar months are used
+ // and the lookup is retried on the next load.
+ final settings = await _service.getMonthStartDay(accessToken: token);
+ if (settings['success'] == true) {
+ _monthStartDay = settings['month_start_day'] as int;
+ range = _rangeFor(period);
+ if (_requestIds[period] == requestId) _inFlight[period] = range;
+ } else if (settings['error'] == 'unauthorized') {
+ unauthorized = true;
+ }
+ }
+ if (!unauthorized) {
+ result = await _service.getCashFlow(accessToken: token, range: range);
+ unauthorized = result['error'] == 'unauthorized';
+ }
+ }
+ } catch (_) {
+ // A failed token refresh (or storage error) is a failed load.
+ result = null;
+ }
+ if (!mounted || requestId != _requestIds[period]) return;
+ _inFlight.remove(period);
+ // Connectivity may have dropped while the request was in flight.
+ final wentOffline = offline || (_connectivity()?.isOffline ?? false);
+
+ setState(() {
+ final visible = period == _period;
+ if (visible) _loading = false;
+ if (result != null && result['success'] == true) {
+ _reports[period] = result['report'] as CashFlowReport;
+ _reportRanges[period] = range;
+ _stale.remove(period);
+ } else {
+ if (visible) {
+ _offline = wentOffline;
+ _failed = !wentOffline;
+ }
+ if (_reports.containsKey(period)) _stale.add(period);
+ }
+ });
+ if (unauthorized) await _handleUnauthorized();
+ }
+
+ void _selectPeriod(CashFlowPeriod period) {
+ if (period == _period) return;
+ setState(() {
+ _period = period;
+ _loading = _inFlight.containsKey(period);
+ _failed = false;
+ _offline = false;
+ });
+ _load();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final l = AppLocalizations.of(context);
+ final report = _visibleReport(_period);
+
+ return Scaffold(
+ appBar: AppBar(title: Text(l.cashFlowTitle)),
+ body: RefreshIndicator(
+ onRefresh: () => _load(force: true),
+ child: ListView(
+ // Keep pull-to-refresh available even when content is short.
+ physics: const AlwaysScrollableScrollPhysics(),
+ padding: const EdgeInsets.fromLTRB(
+ SureSpacing.xl,
+ SureSpacing.md,
+ SureSpacing.xl,
+ SureSpacing.huge,
+ ),
+ children: [
+ _PeriodSelector(selected: _period, onSelected: _selectPeriod),
+ const SizedBox(height: SureSpacing.xl),
+ if (report == null)
+ _buildPlaceholder(context)
+ else ...[
+ _SummaryCard(
+ report: report,
+ stale: _stale.contains(_period),
+ ),
+ const SizedBox(height: SureSpacing.xl),
+ if (report.isEmpty)
+ _MessageState(
+ icon: SureIcons.receipt,
+ title: l.cashFlowEmpty,
+ subtitle: l.cashFlowEmptySubtitle,
+ )
+ else ...[
+ SureSegmentedControl<CashFlowSide>(
+ selected: _side,
+ onChanged: (side) => setState(() => _side = side),
+ segments: [
+ SureSegment(
+ value: CashFlowSide.expense,
+ label: l.cashFlowExpenses,
+ ),
+ SureSegment(
+ value: CashFlowSide.income,
+ label: l.cashFlowIncome,
+ ),
+ ],
+ ),
+ const SizedBox(height: SureSpacing.xl),
+ _CategoryBreakdown(
+ report: report,
+ side: _side,
+ onCategoryTap: (category) => _openCategory(report, category),
+ ),
+ ],
+ ],
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _buildPlaceholder(BuildContext context) {
+ final l = AppLocalizations.of(context);
+ if (_loading) {
+ return const Padding(
+ padding: EdgeInsets.symmetric(vertical: SureSpacing.huge * 2),
+ child: Center(child: CircularProgressIndicator()),
+ );
+ }
+ if (_offline || _failed) {
+ return _MessageState(
+ icon: SureIcons.circleAlert,
+ title: l.cashFlowLoadFailed,
+ subtitle: _offline ? l.cashFlowOffline : null,
+ action: SureButton(
+ label: l.commonTryAgain,
+ onPressed: () => _load(force: true),
+ leading: const SureIcon(SureIcons.refresh, size: 18),
+ ),
+ );
+ }
+ return const SizedBox.shrink();
+ }
+
+ void _openCategory(CashFlowReport report, CashFlowCategory category) {
+ if (!category.canDrillDown) return;
+ Navigator.push(
+ context,
+ MaterialPageRoute(
+ builder: (_) => CashFlowCategoryTransactionsScreen(
+ category: category,
+ range: CashFlowDateRange(report.startDate, report.endDate),
+ service: widget.transactionsService,
+ categoriesService: widget.categoriesService,
+ accessTokenLoader: widget.accessTokenLoader,
+ onUnauthorized: widget.onUnauthorized,
+ ),
+ ),
+ );
+ }
+}
+
+/// Shared money/percent formatting for the cash flow widgets.
+class CashFlowFormat {
+ const CashFlowFormat._();
+
+ static String money(BuildContext context, double amount, String currency) {
+ final locale = Localizations.localeOf(context).toString();
+ try {
+ return NumberFormat.simpleCurrency(
+ locale: locale,
+ name: currency.isEmpty ? null : currency,
+ ).format(amount);
+ } catch (_) {
+ return '${amount.toStringAsFixed(2)} $currency';
+ }
+ }
+
+ /// [percent] is in percentage points (e.g. `24.5` -> `24.5%`).
+ static String percent(BuildContext context, double percent) {
+ final locale = Localizations.localeOf(context).toString();
+ return NumberFormat.decimalPercentPattern(locale: locale, decimalDigits: 1)
+ .format(percent / 100);
+ }
+}
+
+class _PeriodSelector extends StatelessWidget {
+ const _PeriodSelector({required this.selected, required this.onSelected});
+
+ final CashFlowPeriod selected;
+ final ValueChanged<CashFlowPeriod> onSelected;
+
+ static String label(AppLocalizations l, CashFlowPeriod period) {
+ switch (period) {
+ case CashFlowPeriod.currentMonth:
+ return l.cashFlowPeriodCurrentMonth;
+ case CashFlowPeriod.lastMonth:
+ return l.cashFlowPeriodLastMonth;
+ case CashFlowPeriod.last30Days:
+ return l.cashFlowPeriodLast30Days;
+ case CashFlowPeriod.last90Days:
+ return l.cashFlowPeriodLast90Days;
+ case CashFlowPeriod.currentYear:
+ return l.cashFlowPeriodCurrentYear;
+ case CashFlowPeriod.last365Days:
+ return l.cashFlowPeriodLast365Days;
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final l = AppLocalizations.of(context);
+ return SingleChildScrollView(
+ scrollDirection: Axis.horizontal,
+ child: Row(
+ children: [
+ for (final period in CashFlowPeriod.values) ...[
+ if (period != CashFlowPeriod.values.first)
+ const SizedBox(width: SureSpacing.md),
+ SureChip(
+ key: ValueKey('cashFlowPeriod_${period.name}'),
+ label: label(l, period),
+ selected: period == selected,
+ onSelected: (_) => onSelected(period),
+ ),
+ ],
+ ],
+ ),
+ );
+ }
+}
+
+class _SummaryCard extends StatelessWidget {
+ const _SummaryCard({required this.report, required this.stale});
+
+ final CashFlowReport report;
+ final bool stale;
+
+ @override
+ Widget build(BuildContext context) {
+ final l = AppLocalizations.of(context);
+ final palette = SureColors.of(context).palette;
+ final theme = Theme.of(context);
+ final hidden = context.watch<PrivacyProvider>().hidden;
+ String money(double v) => MoneyMasker.mask(
+ CashFlowFormat.money(context, v, report.currency),
+ hidden: hidden,
+ );
+ final locale = Localizations.localeOf(context).toString();
+ final dates = DateFormat.yMMMd(locale);
+ final rate = report.savingsRate;
+
+ return SureCard(
+ key: const ValueKey('cashFlowSummary'),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ children: [
+ Expanded(
+ child: Text(
+ '${dates.format(report.startDate)} – ${dates.format(report.endDate)}',
+ style: theme.textTheme.labelMedium
+ ?.copyWith(color: palette.textSecondary),
+ ),
+ ),
+ if (stale)
+ Container(
+ padding: const EdgeInsets.symmetric(
+ horizontal: SureSpacing.sm,
+ vertical: 1,
+ ),
+ decoration: BoxDecoration(
+ color: palette.surfaceInset,
+ borderRadius: BorderRadius.circular(4),
+ ),
+ child: Text(
+ l.cashFlowOutdated,
+ style: theme.textTheme.labelSmall?.copyWith(
+ color: palette.textSubdued,
+ fontWeight: SureTokens.weightMedium,
+ ),
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: SureSpacing.lg),
+ Text(
+ l.cashFlowNetSavings,
+ style: theme.textTheme.labelMedium
+ ?.copyWith(color: palette.textSecondary),
+ ),
+ const SizedBox(height: SureSpacing.xs),
+ MoneyText(
+ money(report.netSavings),
+ trend:
+ report.netSavings < 0 ? MoneyTrend.outflow : MoneyTrend.inflow,
+ style: theme.textTheme.headlineSmall
+ ?.copyWith(fontWeight: SureTokens.weightMedium),
+ ),
+ if (rate != null) ...[
+ const SizedBox(height: 2),
+ Text(
+ l.cashFlowSavingsRate(
+ MoneyMasker.mask(
+ CashFlowFormat.percent(context, rate),
+ hidden: hidden,
+ ),
+ ),
+ style: theme.textTheme.bodySmall
+ ?.copyWith(color: palette.textSecondary),
+ ),
+ ],
+ const SizedBox(height: SureSpacing.lg),
+ Divider(height: 1, color: palette.borderSecondary),
+ const SizedBox(height: SureSpacing.lg),
+ Row(
+ children: [
+ Expanded(
+ child: _SummaryStat(
+ label: l.cashFlowIncome,
+ value: money(report.income),
+ trend: MoneyTrend.inflow,
+ ),
+ ),
+ const SizedBox(width: SureSpacing.lg),
+ Expanded(
+ child: _SummaryStat(
+ label: l.cashFlowExpenses,
+ value: money(report.spending),
+ trend: MoneyTrend.outflow,
+ ),
+ ),
+ ],
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+class _SummaryStat extends StatelessWidget {
+ const _SummaryStat({
+ required this.label,
+ required this.value,
+ required this.trend,
+ });
+
+ final String label;
+ final String value;
+ final MoneyTrend trend;
+
+ @override
+ Widget build(BuildContext context) {
+ final palette = SureColors.of(context).palette;
+ final theme = Theme.of(context);
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ label,
+ style: theme.textTheme.labelMedium
+ ?.copyWith(color: palette.textSecondary),
+ ),
+ const SizedBox(height: 2),
+ FittedBox(
+ fit: BoxFit.scaleDown,
+ alignment: AlignmentDirectional.centerStart,
+ child: MoneyText(
+ value,
+ trend: trend,
+ style: theme.textTheme.titleMedium
+ ?.copyWith(fontWeight: SureTokens.weightMedium),
+ ),
+ ),
+ ],
+ );
+ }
+}
+
+class _CategoryBreakdown extends StatelessWidget {
+ const _CategoryBreakdown({
+ required this.report,
+ required this.side,
+ required this.onCategoryTap,
+ });
+
+ final CashFlowReport report;
+ final CashFlowSide side;
+ final ValueChanged<CashFlowCategory> onCategoryTap;
+
+ @override
+ Widget build(BuildContext context) {
+ final l = AppLocalizations.of(context);
+ final palette = SureColors.of(context).palette;
+ final theme = Theme.of(context);
+ final hidden = context.watch<PrivacyProvider>().hidden;
+ final categories = report.categoriesFor(side);
+ final isIncome = side == CashFlowSide.income;
+ final title =
+ isIncome ? l.cashFlowIncomeByCategory : l.cashFlowExpensesByCategory;
+
+ if (categories.isEmpty) {
+ return _MessageState(
+ icon: SureIcons.shapes,
+ title: isIncome ? l.cashFlowNoIncome : l.cashFlowNoExpenses,
+ );
+ }
+
+ // Categories without a color of their own (e.g. Uncategorized) render
+ // in the neutral subdued token, like the web's gray Uncategorized.
+ Color colorAt(int i) => CashFlowDonutChart.colorFromHex(
+ categories[i].color,
+ palette.textSubdued,
+ );
+ String money(double v) => MoneyMasker.mask(
+ CashFlowFormat.money(context, v, report.currency),
+ hidden: hidden,
+ );
+ String share(double p) => MoneyMasker.mask(
+ CashFlowFormat.percent(context, p),
+ hidden: hidden,
+ );
+
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ SureCard(
+ child: Column(
+ children: [
+ CashFlowDonutChart(
+ key: const ValueKey('cashFlowDonut'),
+ semanticLabel: title,
+ hidden: hidden,
+ segments: [
+ for (var i = 0; i < categories.length; i++)
+ DonutSegment(
+ value: categories[i].amount, color: colorAt(i)),
+ ],
+ center: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ isIncome ? l.cashFlowIncome : l.cashFlowExpenses,
+ style: theme.textTheme.labelMedium
+ ?.copyWith(color: palette.textSecondary),
+ ),
+ const SizedBox(height: 2),
+ FittedBox(
+ fit: BoxFit.scaleDown,
+ child: Text(
+ money(report.totalFor(side)),
+ style: SureMoney.tabular(
+ theme.textTheme.titleLarge?.copyWith(
+ fontWeight: SureTokens.weightMedium,
+ color: palette.textPrimary,
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(height: SureSpacing.xl),
+ SureListGroup(
+ header: title,
+ children: [
+ for (var i = 0; i < categories.length; i++)
+ SureListRow(
+ key: ValueKey('cashFlowCategory_${categories[i].id}'),
+ leading: _CategoryDot(color: colorAt(i)),
+ title: categories[i].name,
+ subtitle: isIncome
+ ? l.cashFlowShareOfIncome(share(categories[i].percentage))
+ : l.cashFlowShareOfExpenses(
+ share(categories[i].percentage)),
+ trailing: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ money(categories[i].amount),
+ style: SureMoney.tabular(
+ theme.textTheme.titleSmall?.copyWith(
+ fontWeight: SureTokens.weightMedium,
+ color: palette.textPrimary,
+ ),
+ ),
+ ),
+ const SizedBox(width: SureSpacing.sm),
+ // Keep amounts aligned whether or not a row drills down.
+ if (categories[i].canDrillDown)
+ SureIcon(
+ SureIcons.chevronRight,
+ size: SureIconSize.md,
+ color: palette.textSubdued,
+ )
+ else
+ const SizedBox(width: SureIconSize.md),
+ ],
+ ),
+ onTap: categories[i].canDrillDown
+ ? () => onCategoryTap(categories[i])
+ : null,
+ ),
+ ],
+ ),
+ ],
+ );
+ }
+}
+
+class _CategoryDot extends StatelessWidget {
+ const _CategoryDot({required this.color});
+
+ final Color color;
+
+ @override
+ Widget build(BuildContext context) {
+ return Container(
+ width: 28,
+ height: 28,
+ decoration: BoxDecoration(
+ color: color.withValues(alpha: 0.12),
+ shape: BoxShape.circle,
+ ),
+ alignment: Alignment.center,
+ child: Container(
+ width: 10,
+ height: 10,
+ decoration: BoxDecoration(color: color, shape: BoxShape.circle),
+ ),
+ );
+ }
+}
+
+class _MessageState extends StatelessWidget {
+ const _MessageState({
+ required this.icon,
+ required this.title,
+ this.subtitle,
+ this.action,
+ });
+
+ final String icon;
+ final String title;
+ final String? subtitle;
+ final Widget? action;
+
+ @override
+ Widget build(BuildContext context) {
+ final palette = SureColors.of(context).palette;
+ final theme = Theme.of(context);
+ return Padding(
+ padding: const EdgeInsets.symmetric(
+ vertical: SureSpacing.huge,
+ horizontal: SureSpacing.xl,
+ ),
+ child: Column(
+ children: [
+ SureIcon(icon, size: SureIconSize.xxl, color: palette.textSubdued),
+ const SizedBox(height: SureSpacing.lg),
+ Text(
+ title,
+ textAlign: TextAlign.center,
+ style: theme.textTheme.titleMedium,
+ ),
+ if (subtitle != null) ...[
+ const SizedBox(height: SureSpacing.sm),
+ Text(
+ subtitle!,
+ textAlign: TextAlign.center,
+ style: theme.textTheme.bodyMedium
+ ?.copyWith(color: palette.textSecondary),
+ ),
+ ],
+ if (action != null) ...[
+ const SizedBox(height: SureSpacing.xl),
+ action!,
+ ],
+ ],
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/screens/more_screen.dart b/mobile/lib/screens/more_screen.dart
index 60b89d656b..1c9f459037 100644
--- a/mobile/lib/screens/more_screen.dart
+++ b/mobile/lib/screens/more_screen.dart
@@ -5,6 +5,7 @@ import '../theme/sure_tokens.dart';
import '../widgets/sure_list_group.dart';
import 'budgets_screen.dart';
import 'calendar_screen.dart';
+import 'cash_flow_screen.dart';
import 'recent_transactions_screen.dart';
class MoreScreen extends StatelessWidget {
@@ -51,6 +52,20 @@ class MoreScreen extends StatelessWidget {
);
},
),
+ SureListRow(
+ leading: _iconBadge(context, Icons.insights),
+ title: l.moreCashFlow,
+ subtitle: l.moreCashFlowSubtitle,
+ showChevron: true,
+ onTap: () {
+ Navigator.push(
+ context,
+ MaterialPageRoute(
+ builder: (context) => const CashFlowScreen(),
+ ),
+ );
+ },
+ ),
SureListRow(
leading: _iconBadge(context, Icons.receipt_long),
title: l.moreRecentTransactions,
diff --git a/mobile/lib/services/cash_flow_service.dart b/mobile/lib/services/cash_flow_service.dart
new file mode 100644
index 0000000000..d886c77a3c
--- /dev/null
+++ b/mobile/lib/services/cash_flow_service.dart
@@ -0,0 +1,106 @@
+import 'dart:convert';
+
+import 'package:http/http.dart' as http;
+
+import '../models/cash_flow.dart';
+import 'api_config.dart';
+import 'transactions_service.dart';
+
+/// Fetches server-calculated cash flow from `GET /api/v1/cash_flow`.
+class CashFlowService {
+ CashFlowService({http.Client? client})
+ : _client = client ?? http.Client(),
+ _ownsClient = client == null;
+
+ final http.Client _client;
+
+ /// Only a client this service created is closed by [close]; an injected
+ /// one belongs to the caller.
+ final bool _ownsClient;
+
+ /// Releases the HTTP client's pooled connections if this service owns it.
+ void close() {
+ if (_ownsClient) _client.close();
+ }
+
+ /// The family's month start day (1..28) from `GET /api/v1/family_settings`,
+ /// which the web's "This month" / "Last month" presets follow.
+ ///
+ /// Returns `{'success': true, 'month_start_day': int}` or
+ /// `{'success': false, 'error': …}` (`'unauthorized'` on 401).
+ Future<Map<String, dynamic>> getMonthStartDay({
+ required String accessToken,
+ }) async {
+ final url = Uri.parse('${ApiConfig.baseUrl}/api/v1/family_settings');
+ try {
+ final response = await _client
+ .get(url, headers: ApiConfig.getAuthHeaders(accessToken))
+ .timeout(const Duration(seconds: 30));
+ if (response.statusCode == 401) {
+ return {'success': false, 'error': 'unauthorized'};
+ }
+ if (response.statusCode == 200) {
+ final data = jsonDecode(response.body);
+ final day = data is Map ? data['month_start_day'] : null;
+ if (day is int && day >= 1 && day <= 28) {
+ return {'success': true, 'month_start_day': day};
+ }
+ }
+ return {'success': false, 'error': 'Failed to load family settings'};
+ } catch (_) {
+ return {'success': false, 'error': 'Failed to load family settings'};
+ }
+ }
+
+ /// Loads the category cash flow graph for an explicit date range
+ /// (`view=sankey&start_date=…&end_date=…`), so every preset period uses the
+ /// same server aggregation the web Sankey and spending views use.
+ ///
+ /// Returns `{'success': true, 'report': CashFlowReport}` or
+ /// `{'success': false, 'error': …}` (`'unauthorized'` on 401), matching the
+ /// other mobile services.
+ Future<Map<String, dynamic>> getCashFlow({
+ required String accessToken,
+ required CashFlowDateRange range,
+ }) async {
+ final url = Uri.parse('${ApiConfig.baseUrl}/api/v1/cash_flow').replace(
+ queryParameters: {
+ 'view': 'sankey',
+ 'start_date': range.startIso,
+ 'end_date': range.endIso,
+ },
+ );
+
+ try {
+ final response = await _client
+ .get(url, headers: ApiConfig.getAuthHeaders(accessToken))
+ .timeout(const Duration(seconds: 30));
+
+ if (response.statusCode == 200) {
+ final data = jsonDecode(response.body);
+ if (data is! Map) {
+ return {'success': false, 'error': 'Unexpected cash flow response'};
+ }
+ return {
+ 'success': true,
+ 'report': CashFlowReport.fromJson(Map<String, dynamic>.from(data)),
+ };
+ } else if (response.statusCode == 401) {
+ return {'success': false, 'error': 'unauthorized'};
+ } else {
+ return {
+ 'success': false,
+ 'error': TransactionsService.errorMessageFromResponseBody(
+ response.body,
+ fallback: 'Failed to load cash flow',
+ ),
+ };
+ }
+ } catch (e) {
+ return {
+ 'success': false,
+ 'error': 'Unable to load cash flow. Please try again later.',
+ };
+ }
+ }
+}
diff --git a/mobile/lib/widgets/cash_flow_donut_chart.dart b/mobile/lib/widgets/cash_flow_donut_chart.dart
new file mode 100644
index 0000000000..996cb2bd79
--- /dev/null
+++ b/mobile/lib/widgets/cash_flow_donut_chart.dart
@@ -0,0 +1,141 @@
+import 'dart:math' as math;
+
+import 'package:flutter/material.dart';
+
+import '../theme/sure_colors.dart';
+
+/// One slice of a [CashFlowDonutChart].
+class DonutSegment {
+ const DonutSegment({required this.value, required this.color});
+
+ /// Nonnegative magnitude; slices are drawn proportionally.
+ final double value;
+ final Color color;
+}
+
+/// Lightweight donut chart (a [CustomPainter], no charting dependency) used by
+/// the cash flow screen, mirroring the web dashboard's outflows donut: one
+/// slice per category with a small gap between slices and an arbitrary
+/// [center] widget (typically the side total).
+///
+/// With [hidden] (privacy mode) only the empty track is drawn: the slice
+/// proportions would give the masked amounts away.
+class CashFlowDonutChart extends StatelessWidget {
+ const CashFlowDonutChart({
+ super.key,
+ required this.segments,
+ this.center,
+ this.size = 200,
+ this.strokeWidth = 18,
+ this.semanticLabel,
+ this.hidden = false,
+ });
+
+ final List<DonutSegment> segments;
+ final Widget? center;
+ final double size;
+ final double strokeWidth;
+ final String? semanticLabel;
+ final bool hidden;
+
+ @override
+ Widget build(BuildContext context) {
+ final palette = SureColors.of(context).palette;
+ return Semantics(
+ label: semanticLabel,
+ image: true,
+ child: SizedBox.square(
+ dimension: size,
+ child: CustomPaint(
+ painter: _DonutPainter(
+ segments: hidden ? const [] : segments,
+ strokeWidth: strokeWidth,
+ trackColor: palette.surfaceInset,
+ ),
+ child: center == null
+ ? null
+ : Center(
+ child: Padding(
+ padding: EdgeInsets.all(strokeWidth + 8),
+ child: center,
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ /// Parses a `#rrggbb` (or `#aarrggbb`) category color; returns [fallback]
+ /// when [hex] is missing or malformed.
+ static Color colorFromHex(String? hex, Color fallback) {
+ if (hex == null) return fallback;
+ var value = hex.trim().replaceFirst('#', '');
+ if (value.length == 6) value = 'FF$value';
+ if (value.length != 8) return fallback;
+ final parsed = int.tryParse(value, radix: 16);
+ return parsed == null ? fallback : Color(parsed);
+ }
+}
+
+class _DonutPainter extends CustomPainter {
+ _DonutPainter({
+ required this.segments,
+ required this.strokeWidth,
+ required this.trackColor,
+ });
+
+ final List<DonutSegment> segments;
+ final double strokeWidth;
+ final Color trackColor;
+
+ // Gap between slices, in radians (~1.5°), like the web donut's padAngle.
+ static const double _gap = 0.026;
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ final rect = Rect.fromCircle(
+ center: size.center(Offset.zero),
+ radius: (math.min(size.width, size.height) - strokeWidth) / 2,
+ );
+ final paint = Paint()
+ ..style = PaintingStyle.stroke
+ ..strokeWidth = strokeWidth
+ ..strokeCap = StrokeCap.butt;
+
+ final total =
+ segments.fold<double>(0, (sum, s) => sum + math.max(0, s.value));
+ if (total <= 0) {
+ canvas.drawArc(rect, 0, math.pi * 2, false, paint..color = trackColor);
+ return;
+ }
+
+ final visible = segments.where((s) => s.value > 0).toList();
+ final gap = visible.length > 1 ? _gap : 0.0;
+ var start = -math.pi / 2;
+ for (final segment in visible) {
+ final sweep = segment.value / total * math.pi * 2;
+ final drawn = math.max(0.0, sweep - gap);
+ if (drawn > 0) {
+ canvas.drawArc(
+ rect, start + gap / 2, drawn, false, paint..color = segment.color);
+ }
+ start += sweep;
+ }
+ }
+
+ @override
+ bool shouldRepaint(covariant _DonutPainter oldDelegate) {
+ if (oldDelegate.strokeWidth != strokeWidth ||
+ oldDelegate.trackColor != trackColor ||
+ oldDelegate.segments.length != segments.length) {
+ return true;
+ }
+ for (var i = 0; i < segments.length; i++) {
+ if (oldDelegate.segments[i].value != segments[i].value ||
+ oldDelegate.segments[i].color != segments[i].color) {
+ return true;
+ }
+ }
+ return false;
+ }
+}
diff --git a/mobile/test/models/cash_flow_test.dart b/mobile/test/models/cash_flow_test.dart
new file mode 100644
index 0000000000..e198f14628
--- /dev/null
+++ b/mobile/test/models/cash_flow_test.dart
@@ -0,0 +1,225 @@
+import 'dart:convert';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:sure_mobile/models/cash_flow.dart';
+
+import '../support/cash_flow_fixture.dart';
+
+void main() {
+ group('CashFlowPeriod.rangeFor', () {
+ final today = DateTime(2026, 3, 15, 18, 30);
+
+ test('matches the web Period presets', () {
+ expect(
+ CashFlowPeriod.currentMonth.rangeFor(today),
+ CashFlowDateRange(DateTime(2026, 3, 1), DateTime(2026, 3, 15)),
+ );
+ expect(
+ CashFlowPeriod.lastMonth.rangeFor(today),
+ CashFlowDateRange(DateTime(2026, 2, 1), DateTime(2026, 2, 28)),
+ );
+ expect(
+ CashFlowPeriod.last30Days.rangeFor(today),
+ CashFlowDateRange(DateTime(2026, 2, 13), DateTime(2026, 3, 15)),
+ );
+ expect(
+ CashFlowPeriod.last90Days.rangeFor(today),
+ CashFlowDateRange(DateTime(2025, 12, 15), DateTime(2026, 3, 15)),
+ );
+ expect(
+ CashFlowPeriod.currentYear.rangeFor(today),
+ CashFlowDateRange(DateTime(2026, 1, 1), DateTime(2026, 3, 15)),
+ );
+ expect(
+ CashFlowPeriod.last365Days.rangeFor(today),
+ CashFlowDateRange(DateTime(2025, 3, 15), DateTime(2026, 3, 15)),
+ );
+ });
+
+ test('last month wraps across the year boundary', () {
+ expect(
+ CashFlowPeriod.lastMonth.rangeFor(DateTime(2026, 1, 5)),
+ CashFlowDateRange(DateTime(2025, 12, 1), DateTime(2025, 12, 31)),
+ );
+ });
+
+ test('This month / Last month follow a custom month start day', () {
+ // Family#custom_month_start_for: on or after the start day the custom
+ // month began this calendar month, before it the previous one.
+ expect(
+ CashFlowPeriod.currentMonth.rangeFor(today, monthStartDay: 10),
+ CashFlowDateRange(DateTime(2026, 3, 10), DateTime(2026, 4, 9)),
+ );
+ expect(
+ CashFlowPeriod.lastMonth.rangeFor(today, monthStartDay: 10),
+ CashFlowDateRange(DateTime(2026, 2, 10), DateTime(2026, 3, 9)),
+ );
+ expect(
+ CashFlowPeriod.currentMonth.rangeFor(today, monthStartDay: 20),
+ CashFlowDateRange(DateTime(2026, 2, 20), DateTime(2026, 3, 19)),
+ );
+ expect(
+ CashFlowPeriod.lastMonth.rangeFor(today, monthStartDay: 20),
+ CashFlowDateRange(DateTime(2026, 1, 20), DateTime(2026, 2, 19)),
+ );
+ });
+
+ test('custom month start wraps across the year boundary', () {
+ final jan = DateTime(2026, 1, 5);
+ expect(
+ CashFlowPeriod.currentMonth.rangeFor(jan, monthStartDay: 25),
+ CashFlowDateRange(DateTime(2025, 12, 25), DateTime(2026, 1, 24)),
+ );
+ expect(
+ CashFlowPeriod.lastMonth.rangeFor(jan, monthStartDay: 25),
+ CashFlowDateRange(DateTime(2025, 11, 25), DateTime(2025, 12, 24)),
+ );
+ });
+
+ test('rolling and yearly presets ignore the month start day', () {
+ for (final period in [
+ CashFlowPeriod.last30Days,
+ CashFlowPeriod.last90Days,
+ CashFlowPeriod.currentYear,
+ CashFlowPeriod.last365Days,
+ ]) {
+ expect(
+ period.rangeFor(today, monthStartDay: 10), period.rangeFor(today));
+ }
+ expect(
+ CashFlowPeriod.currentMonth.rangeFor(today, monthStartDay: 1),
+ CashFlowPeriod.currentMonth.rangeFor(today),
+ );
+ });
+
+ test('formats ISO dates for the API', () {
+ final range =
+ CashFlowDateRange(DateTime(2026, 2, 3), DateTime(2026, 12, 31));
+ expect(range.startIso, '2026-02-03');
+ expect(range.endIso, '2026-12-31');
+ });
+ });
+
+ group('CashFlowReport.fromJson', () {
+ late CashFlowReport report;
+
+ setUp(() {
+ report = CashFlowReport.fromJson(
+ jsonDecode(cashFlowSankeyFixture) as Map<String, dynamic>,
+ );
+ });
+
+ test('reads totals, currency and period', () {
+ expect(report.currency, 'USD');
+ expect(report.startDate, DateTime(2026, 10, 1));
+ expect(report.endDate, DateTime(2026, 10, 19));
+ expect(report.income, 5000);
+ expect(report.spending, 1500);
+ expect(report.netSavings, 3500);
+ expect(report.savingsRate, closeTo(70, 0.001));
+ });
+
+ test('ranks root categories per side, largest first', () {
+ expect(
+ report.incomeCategories.map((c) => c.name), ['Salary', 'Interest']);
+ expect(report.expenseCategories.map((c) => c.name),
+ ['Rent', 'Food & Drink', 'Uncategorized']);
+ expect(report.expenseCategories.first.percentage, 66.7);
+ expect(report.expenseCategories.first.color, '#4da568');
+ });
+
+ test('folds subcategories into their root for drill-down', () {
+ final food =
+ report.expenseCategories.firstWhere((c) => c.name == 'Food & Drink');
+ expect(food.children.map((c) => c.name), ['Groceries']);
+ expect(food.transactionCategoryIds, ['cat_food', 'cat_groceries']);
+ expect(food.canDrillDown, isTrue);
+ });
+
+ test('synthetic buckets without a category id cannot drill down', () {
+ final uncategorized = report.expenseCategories.last;
+ expect(uncategorized.categoryId, isNull);
+ expect(uncategorized.canDrillDown, isFalse);
+ });
+
+ test('drill-down includes subcategories listed on the other side', () {
+ // Groceries refunds outweigh its spending, so the server lists it under
+ // the income counterpart of Food & Drink instead of under its expenses.
+ final json = jsonDecode(cashFlowSankeyFixture) as Map<String, dynamic>;
+ final sankey = json['sankey'] as Map<String, dynamic>;
+ final nodes = sankey['nodes'] as List;
+ final links = sankey['links'] as List;
+ nodes[4] = {
+ 'id': 'income_sub_cat_groceries',
+ 'name': 'Groceries',
+ 'kind': 'income',
+ 'value': '20.0',
+ 'percentage': '100.0',
+ 'category_id': 'cat_groceries',
+ 'color': '#e99537',
+ };
+ nodes.add({
+ 'id': 'income_cat_food',
+ 'name': 'Food & Drink',
+ 'kind': 'income',
+ 'value': '20.0',
+ 'percentage': '0.4',
+ 'category_id': 'cat_food',
+ 'color': '#e99537',
+ });
+ links[3] = {'source': 4, 'target': 8, 'value': '20.0'};
+ links.add({'source': 8, 'target': 0, 'value': '20.0'});
+
+ final r = CashFlowReport.fromJson(json);
+ final expenseFood =
+ r.expenseCategories.firstWhere((c) => c.name == 'Food & Drink');
+ expect(expenseFood.children, isEmpty);
+ expect(expenseFood.transactionCategoryIds, ['cat_food', 'cat_groceries']);
+ final incomeFood =
+ r.incomeCategories.firstWhere((c) => c.name == 'Food & Drink');
+ expect(incomeFood.children.map((c) => c.name), ['Groceries']);
+ expect(incomeFood.transactionCategoryIds, ['cat_food', 'cat_groceries']);
+ final salary = r.incomeCategories.firstWhere((c) => c.name == 'Salary');
+ expect(salary.transactionCategoryIds, ['cat_salary']);
+ });
+
+ test('nonpositive amounts are not listed', () {
+ final json = jsonDecode(cashFlowSankeyFixture) as Map<String, dynamic>;
+ final nodes = (json['sankey'] as Map)['nodes'] as List;
+ for (final n in nodes) {
+ if (n['name'] == 'Groceries') n['value'] = '-15.0';
+ if (n['name'] == 'Interest') n['value'] = '-5.0';
+ }
+ final r = CashFlowReport.fromJson(json);
+ expect(r.incomeCategories.map((c) => c.name), ['Salary']);
+ final food =
+ r.expenseCategories.firstWhere((c) => c.name == 'Food & Drink');
+ expect(food.children, isEmpty);
+ });
+
+ test('structural nodes are not categories', () {
+ final names = [
+ ...report.incomeCategories.map((c) => c.name),
+ ...report.expenseCategories.map((c) => c.name),
+ ];
+ expect(names, isNot(contains('Cash Flow')));
+ expect(names, isNot(contains('Surplus')));
+ });
+
+ test('savings rate is null without positive income', () {
+ final empty = CashFlowReport.fromJson({
+ 'currency': 'EUR',
+ 'period': {'start_date': '2026-01-01', 'end_date': '2026-01-31'},
+ 'sankey': {
+ 'income': '0',
+ 'spending': '0',
+ 'net_savings': '0',
+ 'nodes': <dynamic>[],
+ 'links': <dynamic>[],
+ },
+ });
+ expect(empty.isEmpty, isTrue);
+ expect(empty.savingsRate, isNull);
+ });
+ });
+}
diff --git a/mobile/test/services/cash_flow_service_test.dart b/mobile/test/services/cash_flow_service_test.dart
new file mode 100644
index 0000000000..be470a2b4b
--- /dev/null
+++ b/mobile/test/services/cash_flow_service_test.dart
@@ -0,0 +1,157 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:http/http.dart' as http;
+import 'package:http/testing.dart';
+import 'package:sure_mobile/models/cash_flow.dart';
+import 'package:sure_mobile/services/cash_flow_service.dart';
+import 'package:sure_mobile/services/transactions_service.dart';
+
+import '../support/cash_flow_fixture.dart';
+
+void main() {
+ final range =
+ CashFlowDateRange(DateTime(2026, 10, 1), DateTime(2026, 10, 19));
+
+ group('CashFlowService', () {
+ test('requests the sankey view for an explicit date range', () async {
+ late Uri requested;
+ final service = CashFlowService(
+ client: MockClient((request) async {
+ requested = request.url;
+ return http.Response(cashFlowSankeyFixture, 200);
+ }),
+ );
+
+ final result =
+ await service.getCashFlow(accessToken: 'token', range: range);
+
+ expect(requested.path, '/api/v1/cash_flow');
+ expect(requested.queryParameters, {
+ 'view': 'sankey',
+ 'start_date': '2026-10-01',
+ 'end_date': '2026-10-19',
+ });
+ expect(result['success'], isTrue);
+ final report = result['report'] as CashFlowReport;
+ expect(report.expenseCategories, hasLength(3));
+ });
+
+ test('maps 401 to unauthorized', () async {
+ final service = CashFlowService(
+ client: MockClient((_) async => http.Response('{}', 401)),
+ );
+ final result =
+ await service.getCashFlow(accessToken: 'token', range: range);
+ expect(result, {'success': false, 'error': 'unauthorized'});
+ });
+
+ test('surfaces the API validation message on 422', () async {
+ final service = CashFlowService(
+ client: MockClient((_) async => http.Response(
+ '{"error":"invalid_period","message":"Date ranges require view=sankey"}',
+ 422,
+ )),
+ );
+ final result =
+ await service.getCashFlow(accessToken: 'token', range: range);
+ expect(result['success'], isFalse);
+ expect(result['error'], 'Date ranges require view=sankey');
+ });
+
+ test('returns a generic error on network failure', () async {
+ final service = CashFlowService(
+ client: MockClient((_) async => throw http.ClientException('down')),
+ );
+ final result =
+ await service.getCashFlow(accessToken: 'token', range: range);
+ expect(result['success'], isFalse);
+ expect(
+ result['error'],
+ 'Unable to load cash flow. Please try again later.',
+ );
+ });
+
+ test('reads the family month start day', () async {
+ late Uri requested;
+ final service = CashFlowService(
+ client: MockClient((request) async {
+ requested = request.url;
+ return http.Response('{"month_start_day":15}', 200);
+ }),
+ );
+ final result = await service.getMonthStartDay(accessToken: 'token');
+ expect(requested.path, '/api/v1/family_settings');
+ expect(result, {'success': true, 'month_start_day': 15});
+ });
+
+ test('maps a family settings 401 to unauthorized', () async {
+ final service = CashFlowService(
+ client: MockClient((_) async => http.Response('{}', 401)),
+ );
+ final result = await service.getMonthStartDay(accessToken: 'token');
+ expect(result, {'success': false, 'error': 'unauthorized'});
+ });
+
+ test('rejects a missing or out-of-range month start day', () async {
+ for (final body in [
+ '{}',
+ '{"month_start_day":0}',
+ '{"month_start_day":29}',
+ '{"month_start_day":"15"}'
+ ]) {
+ final service = CashFlowService(
+ client: MockClient((_) async => http.Response(body, 200)),
+ );
+ final result = await service.getMonthStartDay(accessToken: 'token');
+ expect(result['success'], isFalse, reason: body);
+ expect(result['error'], 'Failed to load family settings');
+ }
+ });
+
+ test('close() leaves an injected client open', () async {
+ final client = _TrackingClient();
+ CashFlowService(client: client).close();
+ expect(client.closed, isFalse);
+ });
+ });
+
+ test('TransactionsService filters by period and repeated category ids',
+ () async {
+ late Uri requested;
+ final service = TransactionsService(
+ client: MockClient((request) async {
+ requested = request.url;
+ return http.Response(
+ '{"transactions":[],"pagination":{"page":1,"per_page":50,'
+ '"total_count":0,"total_pages":0}}',
+ 200,
+ );
+ }),
+ );
+
+ final result = await service.getTransactions(
+ accessToken: 'token',
+ page: 1,
+ perPage: 50,
+ startDate: '2026-10-01',
+ endDate: '2026-10-19',
+ categoryIds: const ['cat_food', 'cat_groceries'],
+ );
+
+ expect(result['success'], isTrue);
+ expect(requested.queryParameters['start_date'], '2026-10-01');
+ expect(requested.queryParameters['end_date'], '2026-10-19');
+ expect(requested.queryParametersAll['category_ids[]'],
+ ['cat_food', 'cat_groceries']);
+ });
+}
+
+class _TrackingClient extends http.BaseClient {
+ bool closed = false;
+
+ @override
+ Future<http.StreamedResponse> send(http.BaseRequest request) =>
+ throw UnimplementedError();
+
+ @override
+ void close() => closed = true;
+}
diff --git a/mobile/test/support/cash_flow_fixture.dart b/mobile/test/support/cash_flow_fixture.dart
new file mode 100644
index 0000000000..70f47224ca
--- /dev/null
+++ b/mobile/test/support/cash_flow_fixture.dart
@@ -0,0 +1,37 @@
+/// A `GET /api/v1/cash_flow?view=sankey` response shaped like
+/// `IncomeStatement::Sankey#as_json`: income roots -> Cash Flow -> expense
+/// roots -> expense subcategories, balanced by a Surplus node.
+const String cashFlowSankeyFixture = '''
+{
+ "as_of": "2026-10-19",
+ "time_zone": "America/New_York",
+ "currency": "USD",
+ "period": { "start_date": "2026-10-01", "end_date": "2026-10-19" },
+ "sankey": {
+ "basis": "net_by_category",
+ "income": "5000.0",
+ "spending": "1500.0",
+ "invested": "0.0",
+ "net_savings": "3500.0",
+ "nodes": [
+ { "id": "cash_flow_node", "name": "Cash Flow", "kind": "cash_flow", "value": "5000.0", "percentage": "100.0", "category_id": null, "filter_value": null, "color": null },
+ { "id": "income_cat_salary", "name": "Salary", "kind": "income", "value": "4500.0", "percentage": "90.0", "category_id": "cat_salary", "filter_value": "Salary", "color": "#10a861" },
+ { "id": "income_cat_interest", "name": "Interest", "kind": "income", "value": "500.0", "percentage": "10.0", "category_id": "cat_interest", "filter_value": "Interest", "color": "#6471eb" },
+ { "id": "expense_cat_food", "name": "Food & Drink", "kind": "expense", "value": "400.0", "percentage": "26.7", "category_id": "cat_food", "filter_value": "Food & Drink", "color": "#e99537" },
+ { "id": "expense_sub_cat_groceries", "name": "Groceries", "kind": "expense", "value": "300.0", "percentage": "75.0", "category_id": "cat_groceries", "filter_value": "Groceries", "color": "#e99537" },
+ { "id": "expense_cat_rent", "name": "Rent", "kind": "expense", "value": "1000.0", "percentage": "66.7", "category_id": "cat_rent", "filter_value": "Rent", "color": "#4da568" },
+ { "id": "expense_uncategorized", "name": "Uncategorized", "kind": "expense", "value": "100.0", "percentage": "6.7", "category_id": null, "filter_value": null, "color": null },
+ { "id": "surplus_node", "name": "Surplus", "kind": "surplus", "value": "3500.0", "percentage": "70.0", "category_id": null, "filter_value": null, "color": null }
+ ],
+ "links": [
+ { "source": 1, "target": 0, "value": "4500.0", "percentage": "90.0" },
+ { "source": 2, "target": 0, "value": "500.0", "percentage": "10.0" },
+ { "source": 0, "target": 3, "value": "400.0", "percentage": "26.7" },
+ { "source": 3, "target": 4, "value": "300.0", "percentage": "75.0" },
+ { "source": 0, "target": 5, "value": "1000.0", "percentage": "66.7" },
+ { "source": 0, "target": 6, "value": "100.0", "percentage": "6.7" },
+ { "source": 0, "target": 7, "value": "3500.0", "percentage": "70.0" }
+ ]
+ }
+}
+''';
diff --git a/mobile/test/support/fake_categories_service.dart b/mobile/test/support/fake_categories_service.dart
new file mode 100644
index 0000000000..c222b6a755
--- /dev/null
+++ b/mobile/test/support/fake_categories_service.dart
@@ -0,0 +1,30 @@
+import 'package:sure_mobile/models/category.dart';
+import 'package:sure_mobile/services/categories_service.dart';
+
+/// Answers `GET /api/v1/categories` lookups without the network.
+class FakeCategoriesService extends CategoriesService {
+ FakeCategoriesService({
+ this.subcategories = const [],
+ this.response,
+ });
+
+ /// Returned as the subcategories of any parent.
+ final List<Category> subcategories;
+
+ /// Returned instead of [subcategories] when set (e.g. a failure).
+ final Map<String, dynamic>? response;
+
+ final List<String?> parentIds = [];
+
+ @override
+ Future<Map<String, dynamic>> getCategories({
+ required String accessToken,
+ int? page,
+ int? perPage,
+ bool? rootsOnly,
+ String? parentId,
+ }) async {
+ parentIds.add(parentId);
+ return response ?? {'success': true, 'categories': subcategories};
+ }
+}
diff --git a/mobile/test/widgets/cash_flow_category_transactions_screen_test.dart b/mobile/test/widgets/cash_flow_category_transactions_screen_test.dart
new file mode 100644
index 0000000000..9b4d8e9791
--- /dev/null
+++ b/mobile/test/widgets/cash_flow_category_transactions_screen_test.dart
@@ -0,0 +1,338 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:http/http.dart' as http;
+import 'package:http/testing.dart';
+import 'package:provider/provider.dart';
+import 'package:sure_mobile/l10n/app_localizations.dart';
+import 'package:sure_mobile/models/cash_flow.dart';
+import 'package:sure_mobile/models/category.dart';
+import 'package:sure_mobile/models/transaction.dart';
+import 'package:sure_mobile/providers/privacy_provider.dart';
+import 'package:sure_mobile/screens/cash_flow_category_transactions_screen.dart';
+import 'package:sure_mobile/screens/cash_flow_screen.dart'
+ show AccessTokenLoader;
+import 'package:sure_mobile/services/transactions_service.dart';
+import 'package:sure_mobile/theme/sure_theme.dart';
+
+import '../support/fake_categories_service.dart';
+
+String _page(List<String> names, {required int page, required int pages}) {
+ final rows = [
+ for (final name in names)
+ '{"id":"$name","account":{"id":"a1"},"name":"$name",'
+ '"date":"2026-10-03","amount":"\$1.00","currency":"USD",'
+ '"classification":"expense",'
+ '"category":{"id":"cat_groceries","name":"Groceries"}}',
+ ].join(',');
+ return '{"transactions":[$rows],"pagination":{"page":$page,'
+ '"per_page":50,"total_count":${names.length},"total_pages":$pages}}';
+}
+
+String _row(
+ String name, {
+ String amount = r'$1.00',
+ String classification = 'expense',
+ Map<String, Object> extra = const {},
+}) {
+ final fields = {
+ 'id': name,
+ 'account': {'id': 'a1'},
+ 'name': name,
+ 'date': '2026-10-03',
+ 'amount': amount,
+ 'currency': 'USD',
+ 'classification': classification,
+ 'category': {'id': 'cat_groceries', 'name': 'Groceries'},
+ ...extra,
+ };
+ return jsonEncode(fields);
+}
+
+String _rows(List<String> rows, {required int page, required int pages}) =>
+ '{"transactions":[${rows.join(',')}],"pagination":{"page":$page,'
+ '"per_page":50,"total_count":${rows.length},"total_pages":$pages}}';
+
+void main() {
+ const category = CashFlowCategory(
+ id: 'expense_groceries',
+ name: 'Groceries',
+ side: CashFlowSide.expense,
+ amount: 10,
+ percentage: 100,
+ categoryId: 'cat_groceries',
+ );
+ final range =
+ CashFlowDateRange(DateTime(2026, 10, 1), DateTime(2026, 10, 19));
+
+ Widget harness(
+ TransactionsService service, {
+ FakeCategoriesService? categories,
+ AccessTokenLoader? loader,
+ Future<void> Function(BuildContext context)? onUnauthorized,
+ }) {
+ return ChangeNotifierProvider<PrivacyProvider>.value(
+ value: PrivacyProvider(initialHidden: false),
+ child: MaterialApp(
+ theme: SureTheme.light,
+ localizationsDelegates: AppLocalizations.localizationsDelegates,
+ supportedLocales: AppLocalizations.supportedLocales,
+ home: CashFlowCategoryTransactionsScreen(
+ category: category,
+ range: range,
+ service: service,
+ categoriesService: categories ?? FakeCategoriesService(),
+ accessTokenLoader: loader ?? (_) async => 'token',
+ onUnauthorized: onUnauthorized,
+ ),
+ ),
+ );
+ }
+
+ testWidgets('drops a page that was in flight when the list was refreshed',
+ (tester) async {
+ final pending = <Completer<http.Response>>[];
+ final pages = <String>[];
+ final service = TransactionsService(
+ client: MockClient((request) {
+ pages.add(request.url.queryParameters['page']!);
+ final completer = Completer<http.Response>();
+ pending.add(completer);
+ return completer.future;
+ }),
+ );
+
+ await tester.pumpWidget(harness(service));
+ await tester.pump();
+ expect(pages, ['1']);
+ pending
+ .removeAt(0)
+ .complete(http.Response(_page(['Old A'], page: 1, pages: 2), 200));
+ await tester.pumpAndSettle();
+ expect(find.text('Old A'), findsOneWidget);
+
+ // Page 2 starts loading, then the user pulls to refresh before it lands.
+ final state = tester.state(find.byType(CashFlowCategoryTransactionsScreen))
+ as dynamic;
+ unawaited(state.loadMoreForTest() as Future<void>);
+ await tester.pump();
+ expect(pages, ['1', '2']);
+ final refresh = state.refreshForTest() as Future<void>;
+ await tester.pump();
+ expect(pages, ['1', '2', '1']);
+
+ // The stale page 2 arrives after the refresh started: it is ignored.
+ pending
+ .removeAt(0)
+ .complete(http.Response(_page(['Stale B'], page: 2, pages: 2), 200));
+ await tester.pump();
+ pending
+ .removeAt(0)
+ .complete(http.Response(_page(['Fresh A'], page: 1, pages: 1), 200));
+ await refresh;
+ await tester.pumpAndSettle();
+
+ expect(find.text('Fresh A'), findsOneWidget);
+ expect(find.text('Stale B'), findsNothing);
+ expect(find.text('Old A'), findsNothing);
+ });
+
+ testWidgets('shows the error state when the access token loader throws',
+ (tester) async {
+ final service = TransactionsService(
+ client: MockClient(
+ (_) async => http.Response(_page(['Never'], page: 1, pages: 1), 200)),
+ );
+ await tester.pumpWidget(harness(
+ service,
+ loader: (_) async => throw Exception('storage failed'),
+ ));
+ await tester.pumpAndSettle();
+
+ expect(find.text('Never'), findsNothing);
+ expect(find.text('Try Again'), findsOneWidget);
+ expect(find.byType(CircularProgressIndicator), findsNothing);
+ });
+
+ testWidgets('a 401 logs the session out', (tester) async {
+ var logouts = 0;
+ final service = TransactionsService(
+ client: MockClient((_) async => http.Response('{}', 401)),
+ );
+ await tester.pumpWidget(harness(
+ service,
+ onUnauthorized: (_) async => logouts++,
+ ));
+ await tester.pumpAndSettle();
+
+ expect(logouts, 1);
+ });
+
+ group('subcategories', () {
+ List<List<String>> requested = [];
+ TransactionsService recording() => TransactionsService(
+ client: MockClient((request) async {
+ requested.add(request.url.queryParametersAll['category_ids[]']!);
+ return http.Response(_page(['Row'], page: 1, pages: 1), 200);
+ }),
+ );
+ setUp(() => requested = []);
+
+ testWidgets('includes subcategories the report leaves out', (tester) async {
+ final categories = FakeCategoriesService(subcategories: [
+ Category(id: 'cat_snacks', name: 'Snacks'),
+ ]);
+ await tester.pumpWidget(harness(recording(), categories: categories));
+ await tester.pumpAndSettle();
+
+ expect(categories.parentIds, ['cat_groceries']);
+ expect(requested, [
+ ['cat_groceries', 'cat_snacks'],
+ ]);
+ expect(find.text('Row'), findsOneWidget);
+ });
+
+ testWidgets('falls back to the report categories when the lookup fails',
+ (tester) async {
+ final categories = FakeCategoriesService(
+ response: {'success': false, 'error': 'Failed to fetch categories'},
+ );
+ await tester.pumpWidget(harness(recording(), categories: categories));
+ await tester.pumpAndSettle();
+
+ expect(requested, [
+ ['cat_groceries'],
+ ]);
+ expect(find.text('Row'), findsOneWidget);
+ });
+
+ testWidgets('a 401 from the lookup logs the session out', (tester) async {
+ var logouts = 0;
+ final categories = FakeCategoriesService(
+ response: {'success': false, 'error': 'unauthorized'},
+ );
+ await tester.pumpWidget(harness(
+ recording(),
+ categories: categories,
+ onUnauthorized: (_) async => logouts++,
+ ));
+ await tester.pumpAndSettle();
+
+ expect(logouts, 1);
+ expect(requested, isEmpty);
+ });
+ });
+
+ group('rows the report does not count (#4422 fields)', () {
+ testWidgets('hides split parents, excluded rows and transfer kinds',
+ (tester) async {
+ final service = TransactionsService(
+ client: MockClient((_) async => http.Response(
+ _rows([
+ _row('Plain'),
+ _row('Split parent', extra: {'split_parent': true}),
+ _row('Split child', extra: {'split_parent': false}),
+ _row('Excluded', extra: {'excluded': true}),
+ _row('Transfer', extra: {'kind': 'funds_movement'}),
+ _row('Card payment', extra: {'kind': 'cc_payment'}),
+ _row('One time', extra: {'kind': 'one_time'}),
+ ], page: 1, pages: 1),
+ 200,
+ )),
+ );
+
+ await tester.pumpWidget(harness(service));
+ await tester.pumpAndSettle();
+
+ expect(find.text('Plain'), findsOneWidget);
+ expect(find.text('Split child'), findsOneWidget);
+ for (final hidden in [
+ 'Split parent',
+ 'Excluded',
+ 'Transfer',
+ 'Card payment',
+ 'One time',
+ ]) {
+ expect(find.text(hidden), findsNothing, reason: hidden);
+ }
+ });
+
+ testWidgets('shows a negative loan payment as an outflow', (tester) async {
+ final service = TransactionsService(
+ client: MockClient((_) async => http.Response(
+ _rows([
+ _row(
+ 'Loan',
+ amount: r'-$250.00',
+ classification: 'income',
+ extra: {'kind': 'loan_payment'},
+ ),
+ _row(
+ 'Refund',
+ amount: r'-$5.00',
+ classification: 'income',
+ extra: {'kind': 'standard'},
+ ),
+ ], page: 1, pages: 1),
+ 200,
+ )),
+ );
+
+ await tester.pumpWidget(harness(service));
+ await tester.pumpAndSettle();
+
+ expect(find.text(r'-$250.00'), findsOneWidget);
+ // A refund keeps its direction.
+ expect(find.text(r'+$5.00'), findsOneWidget);
+ });
+
+ testWidgets('fetches the next page when a whole page is filtered out',
+ (tester) async {
+ final pages = <String>[];
+ final service = TransactionsService(
+ client: MockClient((request) async {
+ final page = request.url.queryParameters['page']!;
+ pages.add(page);
+ return http.Response(
+ page == '1'
+ ? _rows([
+ _row('Parent', extra: {'split_parent': true}),
+ ], page: 1, pages: 2)
+ : _rows([_row('Child')], page: 2, pages: 2),
+ 200,
+ );
+ }),
+ );
+
+ await tester.pumpWidget(harness(service));
+ await tester.pumpAndSettle();
+
+ expect(pages, ['1', '2']);
+ expect(find.text('Child'), findsOneWidget);
+ expect(find.text('Parent'), findsNothing);
+ });
+
+ test('older servers without the fields show every row', () {
+ final t = Transaction.fromJson(jsonDecode(_row(
+ 'Old',
+ amount: r'-$5.00',
+ classification: 'income',
+ )) as Map<String, dynamic>);
+ expect(countsInCashFlow(t), isTrue);
+ expect(isCashFlowIncome(t), isTrue);
+ });
+
+ test('an investment contribution counts as an outflow', () {
+ final t = Transaction.fromJson(jsonDecode(_row(
+ 'Contribution',
+ amount: r'-$100.00',
+ classification: 'income',
+ extra: {'kind': 'investment_contribution'},
+ )) as Map<String, dynamic>);
+ expect(countsInCashFlow(t), isTrue);
+ expect(isCashFlowIncome(t), isFalse);
+ });
+ });
+}
diff --git a/mobile/test/widgets/cash_flow_screen_test.dart b/mobile/test/widgets/cash_flow_screen_test.dart
new file mode 100644
index 0000000000..f7617eed6e
--- /dev/null
+++ b/mobile/test/widgets/cash_flow_screen_test.dart
@@ -0,0 +1,493 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:http/http.dart' as http;
+import 'package:http/testing.dart';
+import 'package:provider/provider.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+import 'package:sure_mobile/l10n/app_localizations.dart';
+import 'package:sure_mobile/models/cash_flow.dart';
+import 'package:sure_mobile/providers/privacy_provider.dart';
+import 'package:sure_mobile/screens/cash_flow_category_transactions_screen.dart';
+import 'package:sure_mobile/screens/cash_flow_screen.dart';
+import 'package:sure_mobile/screens/more_screen.dart';
+import 'package:sure_mobile/services/cash_flow_service.dart';
+import 'package:sure_mobile/services/preferences_service.dart';
+import 'package:sure_mobile/services/transactions_service.dart';
+import 'package:sure_mobile/theme/sure_theme.dart';
+import 'package:sure_mobile/widgets/cash_flow_donut_chart.dart';
+import 'package:sure_mobile/widgets/sure_segmented_control.dart';
+
+import '../support/cash_flow_fixture.dart';
+import '../support/fake_categories_service.dart';
+
+void main() {
+ setUp(() {
+ SharedPreferences.setMockInitialValues({});
+ PreferencesService.resetForTest();
+ });
+
+ final requests = <Uri>[];
+ final settingsRequests = <Uri>[];
+
+ // Answers `GET /api/v1/family_settings` (not recorded in [requests]).
+ http.Response? familySettings(http.Request request,
+ {int monthStartDay = 1, int status = 200}) {
+ if (request.url.path != '/api/v1/family_settings') return null;
+ settingsRequests.add(request.url);
+ return http.Response('{"month_start_day":$monthStartDay}', status);
+ }
+
+ CashFlowService service({
+ int status = 200,
+ int monthStartDay = 1,
+ int settingsStatus = 200,
+ }) =>
+ CashFlowService(
+ client: MockClient((request) async {
+ final settings = familySettings(request,
+ monthStartDay: monthStartDay, status: settingsStatus);
+ if (settings != null) return settings;
+ requests.add(request.url);
+ return http.Response(
+ status == 200 ? cashFlowSankeyFixture : '{}',
+ status,
+ headers: {'content-type': 'application/json; charset=utf-8'},
+ );
+ }),
+ );
+
+ // A tall phone-width surface so the whole report is laid out on screen.
+ void usePhoneSurface(WidgetTester tester) {
+ tester.view.physicalSize = const Size(420, 2000);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ }
+
+ Widget harness({
+ required CashFlowService cashFlowService,
+ bool hidden = false,
+ DateTime Function()? clock,
+ AccessTokenLoader? accessTokenLoader,
+ Future<void> Function(BuildContext context)? onUnauthorized,
+ }) {
+ return ChangeNotifierProvider<PrivacyProvider>.value(
+ value: PrivacyProvider(initialHidden: hidden),
+ child: MaterialApp(
+ theme: SureTheme.light,
+ localizationsDelegates: AppLocalizations.localizationsDelegates,
+ supportedLocales: AppLocalizations.supportedLocales,
+ home: CashFlowScreen(
+ service: cashFlowService,
+ transactionsService: TransactionsService(
+ client: MockClient((request) async {
+ requests.add(request.url);
+ return http.Response(
+ '{"transactions":[{"id":"t1","account":{"id":"a1"},'
+ '"name":"Corner Market","date":"2026-10-03",'
+ '"amount":"\$42.10","currency":"USD",'
+ '"classification":"expense",'
+ '"category":{"id":"cat_groceries","name":"Groceries"}}],'
+ '"pagination":{"page":1,"per_page":50,"total_count":1,'
+ '"total_pages":1}}',
+ 200,
+ );
+ }),
+ ),
+ categoriesService: FakeCategoriesService(),
+ accessTokenLoader: accessTokenLoader ?? (_) async => 'token',
+ clock: clock ?? () => DateTime(2026, 10, 19),
+ onUnauthorized: onUnauthorized,
+ ),
+ ),
+ );
+ }
+
+ setUp(() {
+ requests.clear();
+ settingsRequests.clear();
+ });
+
+ testWidgets('shows income, expenses, net savings and ranked expenses',
+ (tester) async {
+ usePhoneSurface(tester);
+ await tester.pumpWidget(harness(cashFlowService: service()));
+ await tester.pumpAndSettle();
+
+ expect(requests.single.queryParameters['start_date'], '2026-10-01');
+ expect(requests.single.queryParameters['end_date'], '2026-10-19');
+
+ expect(find.text(r'$3,500.00'), findsOneWidget); // net savings
+ expect(find.text(r'$5,000.00'), findsOneWidget); // income
+ expect(find.text('70.0% savings rate'), findsOneWidget);
+ expect(find.byKey(const ValueKey('cashFlowDonut')), findsOneWidget);
+
+ expect(find.text('Rent'), findsOneWidget);
+ expect(find.text('66.7% of expenses'), findsOneWidget);
+ // Ranked largest first.
+ final rentY = tester.getTopLeft(find.text('Rent')).dy;
+ final foodY = tester.getTopLeft(find.text('Food & Drink')).dy;
+ expect(rentY, lessThan(foodY));
+ });
+
+ testWidgets('switches to income by category', (tester) async {
+ usePhoneSurface(tester);
+ await tester.pumpWidget(harness(cashFlowService: service()));
+ await tester.pumpAndSettle();
+
+ await tester.tap(find.descendant(
+ of: find.byType(SureSegmentedControl<CashFlowSide>),
+ matching: find.text('Income'),
+ ));
+ await tester.pumpAndSettle();
+
+ expect(find.text('Income by category'.toUpperCase()), findsOneWidget);
+ expect(find.text('Salary'), findsOneWidget);
+ expect(find.text('90.0% of income'), findsOneWidget);
+ });
+
+ testWidgets('changing the period requests that range', (tester) async {
+ usePhoneSurface(tester);
+ await tester.pumpWidget(harness(cashFlowService: service()));
+ await tester.pumpAndSettle();
+
+ await tester.tap(find.byKey(const ValueKey('cashFlowPeriod_lastMonth')));
+ await tester.pumpAndSettle();
+
+ expect(requests.last.queryParameters['start_date'], '2026-09-01');
+ expect(requests.last.queryParameters['end_date'], '2026-09-30');
+
+ // Returning to a loaded period reuses the report.
+ final count = requests.length;
+ await tester.tap(find.byKey(const ValueKey('cashFlowPeriod_currentMonth')));
+ await tester.pumpAndSettle();
+ expect(requests.length, count);
+ });
+
+ testWidgets('privacy mode masks amounts and shares', (tester) async {
+ usePhoneSurface(tester);
+ await tester.pumpWidget(harness(cashFlowService: service(), hidden: true));
+ await tester.pumpAndSettle();
+
+ expect(find.text(r'$3,500.00'), findsNothing);
+ expect(find.text('66.7% of expenses'), findsNothing);
+ expect(find.text('••••% of expenses'), findsWidgets);
+ expect(find.text(r'$••••'), findsWidgets);
+ });
+
+ testWidgets('tapping a category opens its transactions', (tester) async {
+ usePhoneSurface(tester);
+ await tester.pumpWidget(harness(cashFlowService: service()));
+ await tester.pumpAndSettle();
+
+ await tester.tap(find.text('Food & Drink'));
+ await tester.pumpAndSettle();
+
+ final screen = tester.widget<CashFlowCategoryTransactionsScreen>(
+ find.byType(CashFlowCategoryTransactionsScreen),
+ );
+ expect(
+ screen.category.transactionCategoryIds, ['cat_food', 'cat_groceries']);
+ expect(
+ screen.range,
+ CashFlowDateRange(DateTime(2026, 10, 1), DateTime(2026, 10, 19)),
+ );
+
+ final txRequest = requests.last;
+ expect(txRequest.path, '/api/v1/transactions');
+ expect(txRequest.queryParametersAll['category_ids[]'],
+ ['cat_food', 'cat_groceries']);
+ expect(txRequest.queryParameters['start_date'], '2026-10-01');
+ expect(find.text('Corner Market'), findsOneWidget);
+ expect(find.text('-\$42.10'), findsOneWidget);
+ expect(find.textContaining('Groceries'), findsOneWidget);
+ });
+
+ testWidgets('uncategorized is listed but not tappable', (tester) async {
+ usePhoneSurface(tester);
+ await tester.pumpWidget(harness(cashFlowService: service()));
+ await tester.pumpAndSettle();
+
+ await tester.tap(find.text('Uncategorized'));
+ await tester.pumpAndSettle();
+ expect(find.byType(CashFlowCategoryTransactionsScreen), findsNothing);
+ });
+
+ testWidgets('shows an error state with retry when loading fails',
+ (tester) async {
+ usePhoneSurface(tester);
+ await tester.pumpWidget(harness(cashFlowService: service(status: 500)));
+ await tester.pumpAndSettle();
+
+ expect(find.text("Couldn't load cash flow"), findsOneWidget);
+ expect(find.text('Try Again'), findsOneWidget);
+ });
+
+ testWidgets('Try Again reloads the report', (tester) async {
+ usePhoneSurface(tester);
+ var calls = 0;
+ final recovering = CashFlowService(
+ client: MockClient((request) async {
+ final settings = familySettings(request);
+ if (settings != null) return settings;
+ calls++;
+ return calls == 1
+ ? http.Response('{}', 500)
+ : http.Response(cashFlowSankeyFixture, 200);
+ }),
+ );
+ await tester.pumpWidget(harness(cashFlowService: recovering));
+ await tester.pumpAndSettle();
+ expect(calls, 1);
+ expect(find.text("Couldn't load cash flow"), findsOneWidget);
+
+ await tester.tap(find.text('Try Again'));
+ await tester.pumpAndSettle();
+
+ expect(calls, 2);
+ expect(find.text("Couldn't load cash flow"), findsNothing);
+ expect(find.text('Try Again'), findsNothing);
+ expect(find.text(r'$3,500.00'), findsOneWidget);
+ });
+
+ testWidgets('keeps the last report, marked outdated, when a refresh fails',
+ (tester) async {
+ usePhoneSurface(tester);
+ var calls = 0;
+ final flaky = CashFlowService(
+ client: MockClient((request) async {
+ final settings = familySettings(request);
+ if (settings != null) return settings;
+ calls++;
+ return calls == 1
+ ? http.Response(cashFlowSankeyFixture, 200)
+ : http.Response('{}', 503);
+ }),
+ );
+ await tester.pumpWidget(harness(cashFlowService: flaky));
+ await tester.pumpAndSettle();
+ expect(find.text('Outdated'), findsNothing);
+
+ await tester.fling(find.text('Rent'), const Offset(0, 600), 1000);
+ await tester.pumpAndSettle();
+
+ expect(calls, 2);
+ expect(find.text('Outdated'), findsOneWidget);
+ expect(find.text(r'$3,500.00'), findsOneWidget);
+ });
+
+ testWidgets('refetches a cached period once its date range moves',
+ (tester) async {
+ usePhoneSurface(tester);
+ var today = DateTime(2026, 10, 31);
+ await tester
+ .pumpWidget(harness(cashFlowService: service(), clock: () => today));
+ await tester.pumpAndSettle();
+ expect(requests.last.queryParameters['start_date'], '2026-10-01');
+
+ await tester.tap(find.byKey(const ValueKey('cashFlowPeriod_lastMonth')));
+ await tester.pumpAndSettle();
+
+ // The date changes while the screen stays open.
+ today = DateTime(2026, 11, 1);
+ final count = requests.length;
+ await tester.tap(find.byKey(const ValueKey('cashFlowPeriod_currentMonth')));
+ await tester.pumpAndSettle();
+
+ expect(requests.length, count + 1);
+ expect(requests.last.queryParameters['start_date'], '2026-11-01');
+ expect(requests.last.queryParameters['end_date'], '2026-11-01');
+ });
+
+ testWidgets('shows the error state when the access token loader throws',
+ (tester) async {
+ usePhoneSurface(tester);
+ await tester.pumpWidget(harness(
+ cashFlowService: service(),
+ accessTokenLoader: (_) async => throw Exception('storage failed'),
+ ));
+ await tester.pumpAndSettle();
+
+ expect(find.text("Couldn't load cash flow"), findsOneWidget);
+ expect(find.text('Try Again'), findsOneWidget);
+ expect(find.byType(CircularProgressIndicator), findsNothing);
+ });
+
+ testWidgets('More screen links to Cash Flow', (tester) async {
+ usePhoneSurface(tester);
+ await tester.pumpWidget(ChangeNotifierProvider<PrivacyProvider>.value(
+ value: PrivacyProvider(initialHidden: false),
+ child: MaterialApp(
+ theme: SureTheme.light,
+ localizationsDelegates: AppLocalizations.localizationsDelegates,
+ supportedLocales: AppLocalizations.supportedLocales,
+ home: const MoreScreen(),
+ ),
+ ));
+ expect(find.text('Cash Flow'), findsOneWidget);
+ expect(
+ find.text('Income, spending and savings by category'), findsOneWidget);
+
+ await tester.tap(find.text('Cash Flow'));
+ await tester.pumpAndSettle();
+
+ expect(find.byType(CashFlowScreen), findsOneWidget);
+ expect(find.byType(MoreScreen), findsNothing);
+ });
+
+ testWidgets('This month and Last month follow the family month start day',
+ (tester) async {
+ usePhoneSurface(tester);
+ await tester
+ .pumpWidget(harness(cashFlowService: service(monthStartDay: 15)));
+ await tester.pumpAndSettle();
+
+ expect(settingsRequests, hasLength(1));
+ expect(requests.single.queryParameters['start_date'], '2026-10-15');
+ expect(requests.single.queryParameters['end_date'], '2026-11-14');
+
+ await tester.tap(find.byKey(const ValueKey('cashFlowPeriod_lastMonth')));
+ await tester.pumpAndSettle();
+
+ expect(requests.last.queryParameters['start_date'], '2026-09-15');
+ expect(requests.last.queryParameters['end_date'], '2026-10-14');
+ // The setting is looked up once per screen.
+ expect(settingsRequests, hasLength(1));
+ });
+
+ testWidgets('falls back to calendar months when family settings fail',
+ (tester) async {
+ usePhoneSurface(tester);
+ await tester
+ .pumpWidget(harness(cashFlowService: service(settingsStatus: 500)));
+ await tester.pumpAndSettle();
+
+ expect(requests.single.queryParameters['start_date'], '2026-10-01');
+ expect(requests.single.queryParameters['end_date'], '2026-10-19');
+ expect(find.text(r'$3,500.00'), findsOneWidget);
+ });
+
+ testWidgets('a 401 from the report logs the session out', (tester) async {
+ usePhoneSurface(tester);
+ var logouts = 0;
+ await tester.pumpWidget(harness(
+ cashFlowService: service(status: 401),
+ onUnauthorized: (_) async => logouts++,
+ ));
+ await tester.pumpAndSettle();
+
+ expect(logouts, 1);
+ });
+
+ testWidgets('a 401 from family settings logs out without loading the report',
+ (tester) async {
+ usePhoneSurface(tester);
+ var logouts = 0;
+ await tester.pumpWidget(harness(
+ cashFlowService: service(settingsStatus: 401),
+ onUnauthorized: (_) async => logouts++,
+ ));
+ await tester.pumpAndSettle();
+
+ expect(logouts, 1);
+ expect(requests, isEmpty);
+ });
+
+ testWidgets('returning to a period reuses its in-flight request',
+ (tester) async {
+ usePhoneSurface(tester);
+ final pending = <String, Completer<http.Response>>{};
+ final slow = CashFlowService(
+ client: MockClient((request) {
+ final settings = familySettings(request);
+ if (settings != null) return Future.value(settings);
+ requests.add(request.url);
+ final completer = Completer<http.Response>();
+ pending[request.url.queryParameters['start_date']!] = completer;
+ return completer.future;
+ }),
+ );
+ await tester.pumpWidget(harness(cashFlowService: slow));
+ await tester.pump();
+ await tester.pump();
+ expect(requests, hasLength(1)); // This month, 2026-10-01
+
+ await tester.tap(find.byKey(const ValueKey('cashFlowPeriod_lastMonth')));
+ await tester.pump();
+ await tester.pump();
+ expect(requests, hasLength(2));
+
+ // Back to This month while its first request is still running.
+ await tester.tap(find.byKey(const ValueKey('cashFlowPeriod_currentMonth')));
+ await tester.pump();
+ await tester.pump();
+ expect(requests, hasLength(2));
+ expect(find.byType(CircularProgressIndicator), findsOneWidget);
+
+ pending['2026-10-01']!.complete(http.Response(cashFlowSankeyFixture, 200));
+ await tester.pumpAndSettle();
+ expect(find.text(r'$3,500.00'), findsOneWidget);
+
+ pending['2026-09-01']!.complete(http.Response('{}', 500));
+ await tester.pumpAndSettle();
+ expect(find.text(r'$3,500.00'), findsOneWidget);
+ });
+
+ testWidgets('hides a cached report for an old range while it reloads',
+ (tester) async {
+ usePhoneSurface(tester);
+ var today = DateTime(2026, 10, 31);
+ final next = <Completer<http.Response>>[];
+ final service = CashFlowService(
+ client: MockClient((request) {
+ final settings = familySettings(request);
+ if (settings != null) return Future.value(settings);
+ requests.add(request.url);
+ if (next.isNotEmpty) return next.last.future;
+ return Future.value(http.Response(cashFlowSankeyFixture, 200));
+ }),
+ );
+ await tester
+ .pumpWidget(harness(cashFlowService: service, clock: () => today));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('cashFlowPeriod_lastMonth')));
+ await tester.pumpAndSettle();
+
+ today = DateTime(2026, 11, 1);
+ next.add(Completer<http.Response>());
+ await tester.tap(find.byKey(const ValueKey('cashFlowPeriod_currentMonth')));
+ await tester.pump();
+ await tester.pump();
+
+ // October's report is not shown (or tappable) while November loads.
+ expect(find.text('Rent'), findsNothing);
+ expect(find.byType(CircularProgressIndicator), findsOneWidget);
+
+ next.last.complete(http.Response(cashFlowSankeyFixture, 200));
+ await tester.pumpAndSettle();
+ expect(find.text('Rent'), findsOneWidget);
+ });
+
+ testWidgets('privacy mode hides the donut slices', (tester) async {
+ usePhoneSurface(tester);
+ await tester.pumpWidget(harness(cashFlowService: service(), hidden: true));
+ await tester.pumpAndSettle();
+
+ final donut = tester.widget<CashFlowDonutChart>(
+ find.byKey(const ValueKey('cashFlowDonut')));
+ expect(donut.hidden, isTrue);
+ });
+
+ testWidgets('the donut shows its slices outside privacy mode',
+ (tester) async {
+ usePhoneSurface(tester);
+ await tester.pumpWidget(harness(cashFlowService: service()));
+ await tester.pumpAndSettle();
+
+ final donut = tester.widget<CashFlowDonutChart>(
+ find.byKey(const ValueKey('cashFlowDonut')));
+ expect(donut.hidden, isFalse);
+ expect(donut.segments, isNotEmpty);
+ });
+}