The personal finance app for everyone (by everyone)
Ruby
feat(plan): unify Budgets and Goals under a single Plan tab (#2687)
Guillem Arias Fauste9d3879a8599c
diff --git a/app/components/DS/card.html.erb b/app/components/DS/card.html.erbnew file mode 100644index 0000000000..319225f508--- /dev/null+++ b/app/components/DS/card.html.erb@@ -0,0 +1,3 @@+<%= tag.section class: container_classes, **container_opts do %>+ <%= content %>+<% end %>diff --git a/app/components/DS/card.rb b/app/components/DS/card.rbnew file mode 100644index 0000000000..d45b260ff9--- /dev/null+++ b/app/components/DS/card.rb@@ -0,0 +1,19 @@+class DS::Card < DesignSystemComponent+ attr_reader :opts++ # Generic bordered surface panel: bg-container + rounded-xl + shadow-border-xs.+ # Extracted from the Plan hub's budget/goals cards, which had this exact+ # shell hand-rolled twice (#2687 review) — reach for this instead of+ # repeating the class string for the next card-shaped panel.+ def initialize(**opts)+ @opts = opts+ end++ def container_classes+ class_names("bg-container rounded-xl shadow-border-xs p-5 flex flex-col", opts[:class])+ end++ def container_opts+ opts.except(:class)+ end+enddiff --git a/app/components/DS/link.html.erb b/app/components/DS/link.html.erbindex f9c4cff5d7..883b2099a4 100644--- a/app/components/DS/link.html.erb+++ b/app/components/DS/link.html.erb@@ -1,5 +1,5 @@<%= link_to href, **merged_opts do %>- <% if icon && (icon_position != "right") %>+ <% if icon && (icon_position != :right) %><%= helpers.icon(icon, size: size, color: icon_color) %><% end %>@@ -7,7 +7,7 @@<%= text %><% end %>- <% if icon && icon_position == "right" %>+ <% if icon && icon_position == :right %><%= helpers.icon(icon, size: size, color: icon_color) %><% end %>diff --git a/app/controllers/budgets_controller.rb b/app/controllers/budgets_controller.rbindex af41784114..5a31660051 100644--- a/app/controllers/budgets_controller.rb+++ b/app/controllers/budgets_controller.rb@@ -7,7 +7,7 @@ class BudgetsController < ApplicationControllerdef show@source_budget = @budget.most_recent_initialized_budget unless @budget.initialized?- @breadcrumbs = [ [ t("breadcrumbs.home"), root_path ], [ t("breadcrumbs.budgets"), nil ] ]+ @breadcrumbs = plan_breadcrumb_prefix + [ [ t("breadcrumbs.budgets"), nil ] ]enddef editdiff --git a/app/controllers/concerns/breadcrumbable.rb b/app/controllers/concerns/breadcrumbable.rbindex f2ff122824..9cb3a95406 100644--- a/app/controllers/concerns/breadcrumbable.rb+++ b/app/controllers/concerns/breadcrumbable.rb@@ -19,4 +19,13 @@ module Breadcrumbable[ I18n.t("breadcrumbs.#{controller_name}", default: controller_name.titleize), nil ]]end++ # Trail prefix for pages living under the Plan hub (budgets, goals).+ # Preview users reach them through /plan, so their trail starts+ # Home > Plan; without the flag it's the plain Home prefix.+ def plan_breadcrumb_prefix+ prefix = [ [ I18n.t("breadcrumbs.home"), root_path ] ]+ prefix << [ I18n.t("breadcrumbs.plan"), plan_path ] if preview_features_enabled?+ prefix+ endenddiff --git a/app/controllers/goals_controller.rb b/app/controllers/goals_controller.rbindex ae0ccb8b27..ddb3896eba 100644--- a/app/controllers/goals_controller.rb+++ b/app/controllers/goals_controller.rb@@ -2,11 +2,10 @@ class GoalsController < ApplicationControllerbefore_action :require_preview_features!before_action :set_goal, only: %i[show edit update destroy pause resume complete archive unarchive reopen]- FUNDABLE_TYPES = %w[Depository Investment].freeze+ FUNDABLE_TYPES = Goal::FUNDABLE_ACCOUNT_TYPESrescue_from ActiveRecord::RecordNotFound, with: :goal_not_foundSTATE_FILTERS = %w[all active paused completed archived].freeze- ACTIVE_STATUS_RANK = { behind: 0, on_track: 1, no_target_date: 2 }.freezedef indexstate_counts = Current.family.goals.group(:state).count@@ -14,12 +13,10 @@ class GoalsController < ApplicationControllerh[state] = state == "all" ? state_counts.values.sum : (state_counts[state] || 0)end- all_goals = Current.family.goals- .alphabetically- .includes(:open_pledges, :goal_accounts, linked_accounts: :account_providers)- .to_a- @active_goals = all_goals.reject { |g| %w[completed archived].include?(g.state) }- .sort_by { |g| [ g.paused? ? 3 : ACTIVE_STATUS_RANK.fetch(g.status, 4), g.name.downcase ] }+ # Preloads + the family-wide backing-math injection (N+1 guard) live in+ # Goal.prepared_for, shared with the Plan hub's active_prepared_for.+ all_goals = Goal.prepared_for(Current.family)+ @active_goals = Goal.active_display_sort(all_goals.reject { |g| %w[completed archived].include?(g.state) })@completed_goals = all_goals.select { |g| g.state == "completed" }.sort_by { |g| g.name.downcase }@archived_goals = all_goals.select { |g| g.state == "archived" }# Completed goals join the chip-filterable grid below the active ones@@ -28,29 +25,16 @@ class GoalsController < ApplicationController# entirely (rendered with filterable: false).@grid_goals = @active_goals + @completed_goals- # One family-wide earmark-pool + market-flows query injected into every- # rendered goal so the backing math doesn't fire a query per card (N+1).- pooled = Goal.pooled_allocations_for(Current.family)- flows = Goal.market_flows_for(Current.family)- (@grid_goals + @archived_goals).each do |goal|- goal.pooled_allocations = pooled- goal.market_flows = flows- end-@linkable_account_count = Current.user.accessible_accounts.where(accountable_type: FUNDABLE_TYPES).visible.count@kpi = kpi_payload(@active_goals)@any_pending_pledge = @active_goals.any? { |g| g.open_pledges.any? }@show_search = @grid_goals.size > 6- @breadcrumbs = [- [ t("breadcrumbs.home"), root_path ],- [ t("goals.index.title"), nil ]- ]+ @breadcrumbs = plan_breadcrumb_prefix + [ [ t("goals.index.title"), nil ] ]enddef show@open_pledges = @goal.open_pledges.reverse_chronological.to_a- @breadcrumbs = [- [ t("breadcrumbs.home"), root_path ],+ @breadcrumbs = plan_breadcrumb_prefix + [[ t("goals.index.title"), goals_path ],[ @goal.name, nil ]]@@ -62,8 +46,7 @@ class GoalsController < ApplicationControllercurrency: Current.family.primary_currency_code)@linkable_accounts = linkable_accounts_for_new- @breadcrumbs = [- [ t("breadcrumbs.home"), root_path ],+ @breadcrumbs = plan_breadcrumb_prefix + [[ t("goals.index.title"), goals_path ],[ t("goals.new.heading"), nil ]]@@ -257,11 +240,18 @@ class GoalsController < ApplicationControllerelse :flatend+ # behind_pace? excludes paused goals — pausing stops the pace clock,+ # so a paused-but-behind goal belongs in the paused count (below),+ # not in "N behind" or the "needs this month" sum. Keeps this tile+ # consistent with the Plan hub's summary (Goal.summary_for).needs = active_goals- .select { |g| g.status == :behind }+ .select(&:behind_pace?).sum { |g| g.monthly_target_amount.to_d }- behind = active_goals.count { |g| g.status == :behind }- on_track = active_goals.count { |g| g.status == :on_track }+ behind = active_goals.count(&:behind_pace?)+ # Paused goals are excluded from the on-track numerator for the same+ # reason they're excluded from tracked_total below — otherwise the+ # "X of Y" fraction could exceed its own denominator.+ on_track = active_goals.count { |g| !g.paused? && g.status == :on_track }reached = active_goals.count { |g| g.status == :reached }no_date = active_goals.count { |g| g.status == :no_target_date }paused = active_goals.count(&:paused?)diff --git a/app/controllers/plans_controller.rb b/app/controllers/plans_controller.rbnew file mode 100644index 0000000000..6b66024311--- /dev/null+++ b/app/controllers/plans_controller.rb@@ -0,0 +1,30 @@+class PlansController < ApplicationController+ # The Plan hub fronts budgets + goals under one nav entry, and only+ # replaces the Budgets entry for preview users (see+ # ApplicationHelper#plan_nav_item). Without the flag, fall through to the+ # budgets flow so a shared /plan link still lands somewhere sensible.+ before_action :redirect_to_budgets_unless_preview++ def show+ @budget = Budget.find_or_bootstrap(Current.family, start_date: Date.current, user: Current.user)+ @top_budget_categories = @budget.initialized? ? @budget.top_spending_categories : []++ @goals = Goal.active_prepared_for(Current.family)+ @goals_summary = Goal.summary_for(@goals, currency: Current.family.primary_currency_code)+ # Includes completed/archived goals: the hub is the only route to the+ # goals index for preview users, so the "All goals" link must survive+ # an empty *active* list.+ @family_has_goals = @goals.any? || Current.family.goals.exists?+ @linkable_account_count = Current.user.accessible_accounts+ .where(accountable_type: Goal::FUNDABLE_ACCOUNT_TYPES)+ .visible+ .count++ @breadcrumbs = [ [ t("breadcrumbs.home"), root_path ], [ t("breadcrumbs.plan"), nil ] ]+ end++ private+ def redirect_to_budgets_unless_preview+ redirect_to budgets_path unless preview_features_enabled?+ end+enddiff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rbindex 324d96b550..d8d92c0316 100644--- a/app/helpers/application_helper.rb+++ b/app/helpers/application_helper.rb@@ -87,6 +87,33 @@ module ApplicationHelperitem.merge(preview: true)end+ # Budgets and Goals share one nav slot. Preview users get the "Plan" hub+ # entry fronting both (it stays lit while browsing either subpage, since+ # page_active? is a path-prefix match and /budgets · /goals don't share+ # the /plan prefix). Everyone else gets exactly the pre-Plan Budgets+ # entry — Goals was already hidden without the flag, so their nav is+ # unchanged.+ def plan_nav_item+ if preview_features_enabled?+ {+ name: t("layouts.application.nav.plan"),+ path: plan_path,+ icon: "compass",+ icon_custom: false,+ active: page_active?(plan_path) || page_active?(budgets_path) || page_active?(goals_path),+ preview: true+ }+ else+ {+ name: t("layouts.application.nav.budgets"),+ path: budgets_path,+ icon: "map",+ icon_custom: false,+ active: page_active?(budgets_path)+ }+ end+ end+# Wrapper around I18n.l to support custom date formatsdef format_date(object, format = :default, options = {})date = object.to_datediff --git a/app/models/budget.rb b/app/models/budget.rbindex a229def0e1..4c6ced03c7 100644--- a/app/models/budget.rb+++ b/app/models/budget.rb@@ -188,6 +188,25 @@ class Budget < ApplicationRecordendend+ # Whole days from today through the period's last day (today counts).+ # 0 once the period is over. Also feeds+ # BudgetCategory#suggested_daily_spending's per-day split.+ def days_remaining+ [ (end_date - Date.current).to_i + 1, 0 ].max+ end++ # Biggest parent categories by what's actually been spent this period,+ # falling back to allocation size early in the month before spending+ # lands. Categories with neither spend nor an allocation are noise in a+ # summary. (The budget_categories association preloads :category.)+ def top_spending_categories(limit: 4)+ budget_categories+ .reject(&:subcategory?)+ .reject { |bc| bc.actual_spending.to_d.zero? && bc.budgeted_spending.to_d.zero? }+ .sort_by { |bc| [ -bc.actual_spending.to_d, -bc.budgeted_spending.to_d ] }+ .first(limit)+ end+def previous_budget_paramprevious_date = start_date - 1.monthreturn nil unless self.class.budget_date_valid?(previous_date, family: family)diff --git a/app/models/budget_category.rb b/app/models/budget_category.rbindex ec4930623c..ddf069214b 100644--- a/app/models/budget_category.rb+++ b/app/models/budget_category.rb@@ -200,7 +200,7 @@ class BudgetCategory < ApplicationRecordreturn nil unless available_to_spend > 0return nil unless budget.current?- days_remaining = (budget.end_date - Date.current).to_i + 1+ days_remaining = budget.days_remainingreturn nil unless days_remaining > 0{diff --git a/app/models/goal.rb b/app/models/goal.rbindex 51935a86e5..a2578b78b9 100644--- a/app/models/goal.rb+++ b/app/models/goal.rb@@ -33,6 +33,13 @@ class Goal < ApplicationRecordmonetize :target_amount+ # Account types that can back a goal (see linked_accounts_must_be_fundable).+ FUNDABLE_ACCOUNT_TYPES = %w[Depository Investment].freeze++ # Display order for active (non-completed/non-archived) goals: behind+ # first, then on-track, then open-ended. Paused sorts after all of these.+ ACTIVE_DISPLAY_STATUS_RANK = { behind: 0, on_track: 1, no_target_date: 2 }.freeze+scope :alphabetically, -> { order(Arel.sql("LOWER(name) ASC")) }scope :active_first, lambda {order(Arel.sql("CASE state WHEN 'active' THEN 0 WHEN 'paused' THEN 1 WHEN 'completed' THEN 2 ELSE 3 END"))@@ -73,6 +80,81 @@ class Goal < ApplicationRecordattr_writer :market_flows+ # Family-wide map of each linked account's net inflow over the trailing+ # 90 days (account_id => net Entry#amount sum) — the same aggregate #pace+ # computes per goal. Injected alongside pooled_allocations/market_flows so+ # sorting/rendering N goals (active_display_sort calls goal.status, which+ # reaches #pace for any goal with a target_date) fires one grouped query+ # instead of one Entry.sum per goal.+ def self.pace_for(family)+ account_ids = GoalAccount.joins(:goal).where(goals: { family_id: family.id }).distinct.pluck(:account_id)+ return {} if account_ids.empty?++ Entry+ .joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'")+ .where(account_id: account_ids, date: 90.days.ago.to_date..Date.current)+ .where(excluded: false)+ .merge(Transaction.excluding_pending)+ .group(:account_id)+ .sum(:amount)+ end++ attr_writer :pooled_pace++ # Goals loaded ready to render: association preloads for the card/row+ # partials plus the family-wide pooled-allocations + market-flows injection+ # so the per-goal backing math doesn't fire a query per row (N+1). Pass a+ # narrower scope to limit which of the family's goals are loaded.+ def self.prepared_for(family, scope: family.goals)+ goals = scope.alphabetically+ .includes(:open_pledges, :goal_accounts, linked_accounts: :account_providers)+ .to_a+ inject_backing_math!(goals, family)+ goals+ end++ # One family-wide earmark-pool + market-flows + pace read shared across+ # every goal in the list (see pooled_allocations_for / market_flows_for /+ # pace_for).+ def self.inject_backing_math!(goals, family)+ pooled = pooled_allocations_for(family)+ flows = market_flows_for(family)+ pace_map = pace_for(family)+ goals.each do |goal|+ goal.pooled_allocations = pooled+ goal.market_flows = flows+ goal.pooled_pace = pace_map+ end+ end++ # Display order shared by the goals index and the Plan hub: behind first,+ # then on-track, then open-ended, paused last, name as tie-breaker.+ def self.active_display_sort(goals)+ goals.sort_by { |goal| [ goal.paused? ? 3 : ACTIVE_DISPLAY_STATUS_RANK.fetch(goal.status, 4), goal.name.downcase ] }+ end++ # Active goals ready to render outside the goals index (e.g. the Plan hub).+ def self.active_prepared_for(family)+ active_display_sort(+ prepared_for(family, scope: family.goals.where.not(state: %w[completed archived]))+ )+ end++ # Aggregates for a summary card over an already-prepared goal list. Money+ # sums only make sense in one currency, so goals denominated differently+ # stay in the caller's row list but out of the totals.+ def self.summary_for(goals, currency:)+ summable = goals.select { |goal| goal.currency == currency }+ targeted = summable.select { |goal| goal.target_amount.to_d.positive? }++ {+ saved_money: Money.new(summable.sum { |goal| goal.current_balance.to_d }, currency),+ target_money: Money.new(targeted.sum { |goal| goal.target_amount.to_d }, currency),+ behind_count: goals.count(&:behind_pace?),+ pending_count: goals.sum { |goal| goal.open_pledges.size }+ }+ end+aasm column: :state doafter_all_transitions :reset_state_dependent_caches!@@ -212,13 +294,7 @@ class Goal < ApplicationRecord@pace = if linked_accounts.empty?0else- account_ids = linked_accounts.map(&:id)- net = Entry- .joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'")- .where(account_id: account_ids, date: 90.days.ago.to_date..Date.current)- .where(excluded: false)- .merge(Transaction.excluding_pending)- .sum(:amount)+ net = linked_accounts.sum { |account| pooled_pace.fetch(account.id, 0).to_d }(-net.to_d / 3).round(2)endend@@ -334,6 +410,14 @@ class Goal < ApplicationRecordendend+ # The single definition of "behind pace" for counts and copy. Paused goals+ # are excluded even when their raw status computes :behind — pausing stops+ # the pace clock on purpose, so surfacing them as behind (or summing them+ # into "needs this month") would nag the user about a goal they shelved.+ def behind_pace?+ !paused? && status == :behind+ end+# Date of the most-recently-matched pledge's underlying entry. Used by the# show header to display "Last saved N days ago". Anchoring on the entry's# date keeps the readout stable under sync re-runs (which would bump@@ -552,6 +636,10 @@ class Goal < ApplicationRecord@market_flows ||= self.class.market_flows_for(family)end+ def pooled_pace+ @pooled_pace ||= self.class.pace_for(family)+ end+# Cleared after every AASM transition. The state column drives the# display_status / projection_summary memos; without this the same# instance keeps returning the pre-transition value if a controllerdiff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erbindex 08dcd9b266..4a9dd4ef13 100644--- a/app/views/layouts/application.html.erb+++ b/app/views/layouts/application.html.erb@@ -10,8 +10,7 @@ else{ name: t(".nav.home"), path: root_path, icon: "pie-chart", icon_custom: false, active: page_active?(root_path) },{ name: t(".nav.transactions"), path: transactions_path, icon: "credit-card", icon_custom: false, active: page_active?(transactions_path) },{ name: t(".nav.reports"), path: reports_path, icon: "chart-bar", icon_custom: false, active: page_active?(reports_path) },- { name: t(".nav.budgets"), path: budgets_path, icon: "map", icon_custom: false, active: page_active?(budgets_path) },- preview_gated_nav_item({ name: t(".nav.goals"), path: goals_path, icon: "piggy-bank", icon_custom: false, active: page_active?(goals_path) }),+ plan_nav_item,{ name: t(".nav.assistant"), path: chats_path, icon: "icon-assistant", icon_custom: true, active: page_active?(chats_path), mobile_only: true }].compactend %>diff --git a/app/views/plans/_budget_card.html.erb b/app/views/plans/_budget_card.html.erbnew file mode 100644index 0000000000..216ebc23c9--- /dev/null+++ b/app/views/plans/_budget_card.html.erb@@ -0,0 +1,110 @@+<%# locals: (budget:, top_budget_categories:) %>++<%= render DS::Card.new do %>+ <div class="flex flex-wrap items-center gap-2 mb-4">+ <span class="w-7 h-7 rounded-lg bg-surface-inset text-secondary flex items-center justify-center shrink-0">+ <%= icon("layout-grid", size: "sm") %>+ </span>+ <h2 class="text-sm font-medium text-primary shrink-0"><%= t(".title") %></h2>+ <span class="text-xs text-subdued truncate">· <%= budget.name %></span>++ <% if budget.initialized? %>+ <% if budget.available_to_spend.negative? %>+ <%= render DS::Pill.new(label: t("reports.budget_performance.status.over"), tone: :error, marker: false, icon: "alert-circle") %>+ <% elsif budget.percent_of_budget_spent >= 90 %>+ <%= render DS::Pill.new(label: t("reports.budget_performance.status.warning"), tone: :warning, marker: false, icon: "alert-triangle") %>+ <% else %>+ <%= render DS::Pill.new(label: t("reports.budget_performance.status.good"), tone: :success, marker: false, icon: "check-circle") %>+ <% end %>++ <div class="ml-auto shrink-0">+ <%# The budget donut's trailing pencil (_budget_donut.html.erb) labels+ the VALUE itself ("$12,850 ✎" — click the number to edit it).+ This button's label is a static action ("Edit budget"), which+ takes a leading icon everywhere else in the app: the categories+ "Edit" on this same page (budgets/show.html.erb) and "Edit+ split" (transactions/show.html.erb) both do. %>+ <%= render DS::Link.new(+ text: t(".edit_budget"),+ variant: "secondary",+ size: "sm",+ icon: "pencil",+ href: edit_budget_path(budget)+ ) %>+ </div>+ <% end %>+ </div>++ <% if budget.initialized? %>+ <div class="flex items-baseline gap-2">+ <span class="text-3xl font-medium text-primary tabular-nums privacy-sensitive">+ <%= format_money(budget.actual_spending_money) %>+ </span>+ <span class="text-sm text-subdued privacy-sensitive">+ <%= t(".of_total", total: format_money(budget.budgeted_spending_money)) %>+ </span>+ </div>+ <p class="text-xs text-subdued mt-1 mb-4">+ <%= t(".days_left", count: budget.days_remaining) %> · <%= t(".percent_used", percent: budget.percent_of_budget_spent.round) %>+ </p>++ <div class="h-1.5 bg-container-inset rounded-full overflow-hidden">+ <div class="h-full rounded-full <%= budget.available_to_spend.negative? ? "bg-destructive" : "bg-inverse" %>"+ style="inline-size: <%= budget.percent_of_budget_spent.clamp(0, 100).round(1) %>%"></div>+ </div>++ <% if top_budget_categories.any? %>+ <p class="mt-6 mb-1 text-[11px] font-medium uppercase tracking-wide text-secondary"><%= t(".top_categories") %></p>+ <div class="flex-1">+ <% top_budget_categories.each_with_index do |budget_category, index| %>+ <div class="flex items-center gap-3 py-2.5 <%= "border-b border-divider" unless index == top_budget_categories.size - 1 %>">+ <div class="w-7 h-7 shrink-0 rounded-full flex items-center justify-center"+ style="background-color: color-mix(in oklab, <%= budget_category.category.color %> 10%, transparent); color: <%= budget_category.category.color %>;">+ <% if budget_category.category.lucide_icon %>+ <%= icon(budget_category.category.lucide_icon, size: "sm", color: "current") %>+ <% else %>+ <%= render DS::FilledIcon.new(+ variant: :text,+ hex_color: budget_category.category.color,+ text: budget_category.category.name,+ size: "sm",+ rounded: true+ ) %>+ <% end %>+ </div>+ <span class="flex-1 min-w-0 text-sm text-primary truncate"><%= budget_category.category.name %></span>+ <div class="hidden @sm:block w-24 shrink-0 h-1 bg-container-inset rounded-full overflow-hidden">+ <% bar_color = budget_category.over_budget? ? "bg-destructive" : (budget_category.near_limit? ? "bg-warning" : "bg-success") %>+ <div class="h-full <%= bar_color %> rounded-full" style="inline-size: <%= budget_category.bar_width_percent %>%"></div>+ </div>+ <span class="shrink-0 text-xs tabular-nums text-primary privacy-sensitive">+ <%= format_money(budget_category.actual_spending_money) %><span class="text-subdued">/<%= format_money(budget_category.budgeted_spending_money) %></span>+ </span>+ </div>+ <% end %>+ </div>+ <% end %>+ <% else %>+ <div class="flex-1 flex flex-col items-center justify-center text-center gap-3 py-10">+ <span class="w-12 h-12 rounded-full bg-surface-inset text-secondary flex items-center justify-center">+ <%= icon("map", size: "md") %>+ </span>+ <p class="text-sm text-secondary max-w-xs"><%= t(".empty_body") %></p>+ <%= render DS::Link.new(+ text: t(".set_up"),+ variant: "primary",+ href: edit_budget_path(budget)+ ) %>+ </div>+ <% end %>++ <%= render DS::Link.new(+ text: t(".view_budget"),+ variant: "secondary",+ href: budget_path(budget),+ icon: "chevron-right",+ icon_position: :right,+ full_width: true,+ class: "mt-5"+ ) %>+<% end %>diff --git a/app/views/plans/_goals_card.html.erb b/app/views/plans/_goals_card.html.erbnew file mode 100644index 0000000000..3b7a533caa--- /dev/null+++ b/app/views/plans/_goals_card.html.erb@@ -0,0 +1,128 @@+<%# locals: (goals:, summary:, linkable_account_count:, family_has_goals:) %>++<%= render DS::Card.new do %>+ <div class="flex flex-wrap items-center gap-2 mb-4">+ <span class="w-7 h-7 rounded-lg bg-surface-inset text-secondary flex items-center justify-center shrink-0">+ <%= icon("target", size: "sm") %>+ </span>+ <h2 class="text-sm font-medium text-primary shrink-0"><%= t(".title") %></h2>+ <% if goals.any? %>+ <span class="text-xs text-subdued">· <%= t(".active_count", count: goals.size) %></span>+ <% end %>+ <% if goals.any? && linkable_account_count > 0 %>+ <div class="ml-auto shrink-0">+ <%# Same weight as the budget card's edit control (DS::Link,+ secondary, sm) so the two cards' header actions read as one+ family, not two different conventions. %>+ <%= render DS::Link.new(+ text: t(".new_goal"),+ variant: "secondary",+ size: "sm",+ icon: "plus",+ href: new_goal_path,+ frame: :modal+ ) %>+ </div>+ <% end %>+ </div>++ <% if goals.empty? %>+ <%# No *active* goals. The family may still have completed/archived ones+ on the goals index, and this card is the only route there for preview+ users (the Goals nav entry is gone) — hence the footer link below. %>+ <div class="flex-1 flex flex-col items-center justify-center text-center gap-3 py-10">+ <span class="w-12 h-12 rounded-full bg-surface-inset text-secondary flex items-center justify-center">+ <%= icon("target", size: "md") %>+ </span>+ <p class="text-sm text-secondary max-w-xs"><%= t("goals.empty_state.body") %></p>+ <% if linkable_account_count > 0 %>+ <%= render DS::Link.new(+ text: t("goals.empty_state.new_goal"),+ variant: "primary",+ href: new_goal_path,+ icon: "plus",+ frame: :modal+ ) %>+ <% else %>+ <%= render DS::Link.new(+ text: t("goals.empty_state.add_account"),+ variant: "primary",+ href: new_account_path(return_to: plan_path),+ icon: "plus"+ ) %>+ <% end %>+ </div>+ <% else %>+ <div class="flex items-baseline gap-2">+ <span class="text-3xl font-medium text-primary tabular-nums privacy-sensitive">+ <%= format_money(summary[:saved_money]) %>+ </span>+ <% if summary[:target_money].positive? %>+ <span class="text-sm text-subdued privacy-sensitive">+ <%= t(".of_targets", total: format_money(summary[:target_money])) %>+ </span>+ <% end %>+ </div>+ <p class="text-xs text-subdued mt-1 mb-4">+ <%+ parts = []+ parts << t(".behind_count", count: summary[:behind_count]) if summary[:behind_count].positive?+ parts << t(".pending_count", count: summary[:pending_count]) if summary[:pending_count].positive?+ %>+ <%= parts.any? ? parts.join(" · ") : t(".all_on_pace") %>+ </p>++ <% if summary[:target_money].positive? %>+ <div class="h-1.5 bg-container-inset rounded-full overflow-hidden">+ <div class="h-full bg-inverse rounded-full"+ style="inline-size: <%= (summary[:saved_money].amount / summary[:target_money].amount * 100).clamp(0, 100).round(1) %>%"></div>+ </div>+ <% end %>++ <p class="mt-6 mb-1 text-[11px] font-medium uppercase tracking-wide text-secondary"><%= t(".active_goals") %></p>+ <div class="flex-1">+ <% shown_goals = goals.first(5) %>+ <% shown_goals.each_with_index do |goal, index| %>+ <%= link_to goal_path(goal), class: "flex items-center gap-3 py-2.5 group #{"border-b border-divider" unless index == shown_goals.size - 1}" do %>+ <%= render Goals::AvatarComponent.new(goal: goal, size: "md") %>+ <div class="flex-1 min-w-0">+ <div class="flex items-center gap-2 mb-1">+ <span class="text-sm font-medium text-primary truncate"><%= goal.name %></span>+ <%= render Goals::StatusPillComponent.new(goal: goal) %>+ <% if goal.open_pledges.any? %>+ <span class="text-xs text-warning shrink-0">· <%= t(".pending_marker") %></span>+ <% end %>+ </div>+ <% if goal.target_amount.to_d.positive? %>+ <div class="h-1 bg-container-inset rounded-full overflow-hidden">+ <div class="h-full <%= goal.status == :behind ? "bg-warning" : "bg-inverse" %> rounded-full"+ style="inline-size: <%= goal.progress_percent.clamp(0, 100) %>%"></div>+ </div>+ <% elsif goal.months_of_runway.present? %>+ <p class="text-xs text-subdued">+ <%= t(".runway", months: goal.months_of_runway, pace: goal.pace_money.format(precision: 0)) %>+ </p>+ <% end %>+ </div>+ <span class="shrink-0 text-xs tabular-nums text-primary privacy-sensitive">+ <%= format_money(goal.current_balance_money) %><% if goal.target_amount.to_d.positive? %><span class="text-subdued">/<%= goal.target_amount_money.format(precision: 0) %></span><% end %>+ </span>+ <%= icon("chevron-right", size: "sm", class: "text-subdued shrink-0") %>+ <% end %>+ <% end %>+ </div>++ <% end %>++ <% if family_has_goals %>+ <%= render DS::Link.new(+ text: t(".all_goals"),+ variant: "secondary",+ href: goals_path,+ icon: "chevron-right",+ icon_position: :right,+ full_width: true,+ class: "mt-5"+ ) %>+ <% end %>+<% end %>diff --git a/app/views/plans/show.html.erb b/app/views/plans/show.html.erbnew file mode 100644index 0000000000..b9f0ba5442--- /dev/null+++ b/app/views/plans/show.html.erb@@ -0,0 +1,17 @@+<%# Plan hub: budgets + goals under one nav entry. Two summary cards+ fronting the existing /budgets and /goals pages — the two features+ share a home here, not a data model. %>+<div class="@container space-y-6 pb-6 lg:pb-12">+ <header>+ <div class="flex items-center gap-2">+ <h1 class="text-2xl font-semibold text-primary"><%= t(".title") %></h1>+ <%= render DS::Pill.new(label: t("shared.preview"), size: :md) %>+ </div>+ <p class="text-sm text-secondary mt-1"><%= t(".subtitle") %></p>+ </header>++ <div class="grid grid-cols-1 @3xl:grid-cols-2 gap-4 items-stretch">+ <%= render "plans/budget_card", budget: @budget, top_budget_categories: @top_budget_categories %>+ <%= render "plans/goals_card", goals: @goals, summary: @goals_summary, linkable_account_count: @linkable_account_count, family_has_goals: @family_has_goals %>+ </div>+</div>diff --git a/config/locales/breadcrumbs/en.yml b/config/locales/breadcrumbs/en.ymlindex 400fc31b7c..a6cb9886a0 100644--- a/config/locales/breadcrumbs/en.yml+++ b/config/locales/breadcrumbs/en.yml@@ -58,6 +58,7 @@ en:payments: Paymentspending_duplicate_merges: Duplicate reviewplaid_items: Plaid+ plan: Planpreferences: Preferencesprofile: Profile Infoprofiles: Profile Infodiff --git a/config/locales/views/layout/en.yml b/config/locales/views/layout/en.ymlindex 49f3125593..4b3e23a3b1 100644--- a/config/locales/views/layout/en.yml+++ b/config/locales/views/layout/en.yml@@ -11,6 +11,7 @@ en:assistant: Assistantbudgets: Budgetshome: Home+ plan: Planreports: Reportsgoals: Goalstransactions: Transactionsdiff --git a/config/locales/views/plans/en.yml b/config/locales/views/plans/en.ymlnew file mode 100644index 0000000000..563ccd93d2--- /dev/null+++ b/config/locales/views/plans/en.yml@@ -0,0 +1,36 @@+---+en:+ plans:+ show:+ title: Plan+ subtitle: Decide where your money goes — what you spend, and what you save.+ budget_card:+ title: This month+ edit_budget: Edit budget+ of_total: of %{total}+ days_left:+ one: 1 day left+ other: "%{count} days left"+ percent_used: "%{percent}% used"+ top_categories: Top categories+ view_budget: View full budget+ empty_body: Set a monthly spending target and per-category limits to see how this month is tracking.+ set_up: Set up this month's budget+ goals_card:+ title: Your goals+ new_goal: New goal+ active_count:+ one: 1 active+ other: "%{count} active"+ of_targets: of %{total} across goals+ behind_count:+ one: 1 behind pace+ other: "%{count} behind pace"+ pending_count:+ one: 1 pending pledge+ other: "%{count} pending pledges"+ all_on_pace: Everything on pace+ active_goals: Active goals+ pending_marker: pending+ runway: "%{months} mo runway · %{pace}/mo"+ all_goals: All goalsdiff --git a/config/routes.rb b/config/routes.rbindex 11a140882c..305b33d07e 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -377,6 +377,9 @@ Rails.application.routes.draw doget :picker, on: :collectionend+ # Hub page fronting budgets + goals under a single "Plan" nav entry.+ resource :plan, only: :show+resources :budgets, only: %i[index show edit update], param: :month_year dopost :copy_previous, on: :memberget :picker, on: :collectiondiff --git a/test/components/DS/card_test.rb b/test/components/DS/card_test.rbnew file mode 100644index 0000000000..5e6f179c3d--- /dev/null+++ b/test/components/DS/card_test.rb@@ -0,0 +1,21 @@+require "test_helper"++class DS::CardTest < ViewComponent::TestCase+ test "renders the shared card shell around yielded content" do+ render_inline(DS::Card.new) { "Panel body" }++ assert_selector "section.bg-container.rounded-xl.shadow-border-xs.p-5.flex.flex-col", text: "Panel body"+ end++ test "merges an extra class without dropping the shell" do+ render_inline(DS::Card.new(class: "items-center")) { "Panel body" }++ assert_selector "section.bg-container.items-center"+ end++ test "forwards non-class options to the section tag" do+ render_inline(DS::Card.new(id: "budget-card")) { "Panel body" }++ assert_selector "section#budget-card"+ end+enddiff --git a/test/controllers/budgets_controller_test.rb b/test/controllers/budgets_controller_test.rbnew file mode 100644index 0000000000..210b4a3329--- /dev/null+++ b/test/controllers/budgets_controller_test.rb@@ -0,0 +1,38 @@+require "test_helper"++class BudgetsControllerTest < ActionDispatch::IntegrationTest+ setup do+ @user = users(:family_admin)+ sign_in @user+ ensure_tailwind_build+ end++ test "index redirects to the current month budget" do+ get budgets_url++ assert_redirected_to budget_path(Budget.date_to_param(Date.current))+ end++ test "show renders the budget page" do+ get budget_url(Budget.date_to_param(Date.current))++ assert_response :success+ end++ test "breadcrumbs include the Plan hub for preview users" do+ @user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => true))++ get budget_url(Budget.date_to_param(Date.current))++ assert_response :success+ assert_select "a[href=?]", plan_path, minimum: 1+ end++ test "renders no Plan links without preview features" do+ get budget_url(Budget.date_to_param(Date.current))++ assert_response :success+ assert_select "a[href=?]", plan_path, count: 0+ assert_select "a[href=?]", budgets_path, minimum: 1+ end+enddiff --git a/test/controllers/plans_controller_test.rb b/test/controllers/plans_controller_test.rbnew file mode 100644index 0000000000..2877399529--- /dev/null+++ b/test/controllers/plans_controller_test.rb@@ -0,0 +1,67 @@+require "test_helper"++class PlansControllerTest < ActionDispatch::IntegrationTest+ setup do+ @user = users(:family_admin)+ @user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => true))+ sign_in @user+ ensure_tailwind_build+ end++ test "redirects users without preview access to budgets" do+ @user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => false))++ get plan_url++ assert_redirected_to budgets_path+ end++ test "renders budget and goals summary cards with drill-in links" do+ get plan_url++ assert_response :success+ assert_match I18n.t("plans.budget_card.title"), response.body+ assert_match I18n.t("plans.goals_card.title"), response.body+ assert_select "a[href=?]", budget_path(Budget.date_to_param(Date.current))+ assert_select "a[href=?]", goals_path+ end++ test "lists active goals with links to their detail pages" do+ get plan_url++ assert_response :success+ goal = goals(:vacation_italy)+ assert_match goal.name, response.body+ assert_select "a[href=?]", goal_path(goal)+ end++ test "shows the goals empty state when the family has no goals" do+ @user.family.goals.destroy_all++ get plan_url++ assert_response :success+ assert_match I18n.t("goals.empty_state.body"), response.body+ assert_select "a[href=?]", goals_path, count: 0+ end++ test "keeps the all-goals link when only completed or archived goals remain" do+ @user.family.goals.each { |goal| goal.update_columns(state: "archived") }++ get plan_url++ assert_response :success+ assert_match I18n.t("goals.empty_state.body"), response.body+ assert_select "a[href=?]", goals_path, minimum: 1+ end++ test "shows the budget setup CTA when the month is uninitialized" do+ budgets(:one).update!(budgeted_spending: nil)++ get plan_url++ assert_response :success+ assert_match I18n.t("plans.budget_card.empty_body"), response.body+ assert_select "a[href=?]", edit_budget_path(Budget.date_to_param(Date.current))+ end+enddiff --git a/test/models/budget_test.rb b/test/models/budget_test.rbindex 26e1b76537..214f48e54b 100644--- a/test/models/budget_test.rb+++ b/test/models/budget_test.rb@@ -507,4 +507,20 @@ class BudgetTest < ActiveSupport::TestCase# Other Investments synthetic categories previously caused this to return 0assert spending >= 75, "Uncategorized actual spending should include the $75 transaction, got #{spending}"end++ test "days_remaining counts today through the end of the period" do+ budget = budgets(:one)++ travel_to budget.start_date do+ assert_equal (budget.end_date - budget.start_date).to_i + 1, budget.days_remaining+ end++ travel_to budget.end_date do+ assert_equal 1, budget.days_remaining+ end++ travel_to budget.end_date + 1.day do+ assert_equal 0, budget.days_remaining+ end+ endenddiff --git a/test/models/goal_test.rb b/test/models/goal_test.rbindex 1b1bd30eee..8427a208bd 100644--- a/test/models/goal_test.rb+++ b/test/models/goal_test.rb@@ -454,4 +454,29 @@ class GoalTest < ActiveSupport::TestCase# net contributed = 10,000 − 2,000 = 8,000; earmark 1,000 ≤ 8,000 → 1,000.assert_equal BigDecimal("1000"), goal.current_balance.to_dend++ test "behind_pace? excludes paused goals even when their raw status is behind" do+ goal = goals(:vacation_italy)+ goal.stubs(:status).returns(:behind)++ assert goal.behind_pace?++ goal.update!(state: "paused")++ assert goal.paused?+ assert_not goal.behind_pace?+ end++ test "summary_for counts behind goals via behind_pace? and sums one currency" do+ behind = goals(:vacation_italy)+ behind.stubs(:status).returns(:behind)+ paused_behind = goals(:emergency_fund)+ paused_behind.update!(state: "paused")+ paused_behind.stubs(:status).returns(:behind)++ summary = Goal.summary_for([ behind, paused_behind ], currency: "USD")++ assert_equal 1, summary[:behind_count]+ assert_kind_of Money, summary[:saved_money]+ endend