The personal finance app for everyone (by everyone)
Ruby
Apply post-close payments to the closed credit card bill first (#4662)
joaocbatista418d86dbd9e6
diff --git a/app/models/credit_card.rb b/app/models/credit_card.rbindex c671b59268..fc5713c4fe 100644--- a/app/models/credit_card.rb+++ b/app/models/credit_card.rb@@ -8,7 +8,7 @@ class CreditCard < ApplicationRecord}.freezeStatementSummary = Data.define(- :balance, :remaining, :charges, :credits, :accrued,+ :balance, :remaining, :charges, :credits, :payments_applied, :accrued, :adjustments,:due_date, :last_due_date, :next_close, :status, :scheduled_payment,:estimated_interest, :monthly_rate)@@ -116,14 +116,14 @@ class CreditCard < ApplicationRecordlast_close = last_statement_close_date(as_of: as_of)return nil if last_close.nil?- sum_entries_in(..last_close)+ statement_ledger(as_of: as_of, last_close: last_close)[:closed]enddef accrued_since_last_close_money(as_of: Date.current)last_close = last_statement_close_date(as_of: as_of)return nil if last_close.nil?- sum_entries_in((last_close + 1)..as_of)+ accrued_after_bill_settlement(statement_ledger(as_of: as_of, last_close: last_close))end# One read of the statement cycle for the Overview tab. The view needs the@@ -134,21 +134,20 @@ class CreditCard < ApplicationRecordreturn nil unless statement_cycle_configured?last_close = last_statement_close_date(as_of: as_of)- balance = last_statement_balance_money(as_of: as_of)- window = (last_close + 1)..as_of- totals = cycle_totals(window)- charges = totals&.dig(:charges)- credits = totals&.dig(:credits)- accrued = totals&.dig(:accrued)+ ledger = statement_ledger(as_of: as_of, last_close: last_close)+ balance = ledger[:closed]+ credits = ledger[:credits]remaining = statement_remaining(balance, credits)last_due_date = payment_due_date_for(last_close)StatementSummary.new(balance: balance,remaining: remaining,- charges: charges,+ charges: ledger[:charges],credits: credits,- accrued: accrued,+ payments_applied: payments_applied_to_open_cycle(ledger),+ accrued: accrued_after_bill_settlement(ledger),+ adjustments: ledger[:adjustments],due_date: statement_due_date(last_due_date, remaining, as_of),last_due_date: last_due_date,next_close: next_statement_close_date(as_of: as_of),@@ -159,68 +158,112 @@ class CreditCard < ApplicationRecord)end- def minimum_payment_shortfall?(as_of: Date.current)+ # Takes the closed balance when the caller already has it, so the Overview+ # does not build the statement cycle a second time.+ def minimum_payment_shortfall?(as_of: Date.current, balance: last_statement_balance_money(as_of: as_of))minimum = minimum_payment_money- balance = last_statement_balance_money(as_of: as_of)return false if minimum.nil? || balance.nil?balance > minimumendprivate- def cycle_totals(window)- summable = summable_entries(window)- return nil if summable.nil?-- charges = BigDecimal(0)- credits = BigDecimal(0)- summable.pluck(:amount).each do |amount|- if amount.positive?- charges += amount- elsif amount.negative?- credits += amount+ # The figures for the statement cycle. Charges and payments come from the+ # entries in the open cycle. What was owed at the close, and what is owed+ # now, come from the account's balance records: the same records the account+ # header reads, so the two cannot disagree, and no entry history has to be+ # replayed. What is left over between them is the balance updates made in the+ # open cycle, which keeps the figures adding up to the current debt.+ #+ # A part is nil when it holds an entry we cannot add up in the account's own+ # currency, or when the balance records have not been built yet.+ def statement_ledger(as_of:, last_close:)+ currency = account.currency+ scoped = account.entries.excluding_pending.excluding_split_parents+ closed_scope = scoped.where(date: ..last_close)+ window_scope = scoped.where(date: (last_close + 1)..as_of)++ closed_known = all_in_currency?(closed_scope, currency)+ window_known = all_in_currency?(window_scope, currency)++ closed = closed_known ? balance_record_on_or_before(last_close, closed_scope) : nil++ transactions = window_scope.where(entryable_type: "Transaction")+ charges = window_known ? BigDecimal(transactions.where("amount > 0").sum(:amount).to_s) : nil+ credits = window_known ? BigDecimal(transactions.where("amount < 0").sum(:amount).to_s) : nil++ # Without a known closed bill there is nothing to measure an update+ # against, so the fallback keeps the net of the open cycle and leaves+ # updates out.+ adjustments = nil+ if window_known && charges && credits+ if closed.nil?+ adjustments = BigDecimal(0)+ else+ current = balance_record_on_or_before(as_of, scoped.where(date: ..as_of))+ adjustments = current && (current.amount - closed.amount - charges - credits)endend{- charges: Money.new(charges, account.currency),- credits: Money.new(credits, account.currency),- accrued: Money.new(charges + credits, account.currency)+ closed: closed,+ charges: charges && Money.new(charges, currency),+ credits: credits && Money.new(credits, currency),+ adjustments: adjustments && Money.new(adjustments, currency)}end- def sum_entries_in(window, amount_sign: nil)- summable = summable_entries(window)- return nil if summable.nil?+ # Every entry in the scope is in the account's currency. Compared by count,+ # because `where.not(currency:)` never matches an entry with no currency.+ def all_in_currency?(scope, currency)+ scope.where(currency: currency).count == scope.count+ end- amount_scope = case amount_sign- when :positive then summable.where("amount > 0")- when :negative then summable.where("amount < 0")- else summable- end+ # The balance the account had on the given date, or on the nearest earlier+ # date that has one. Nothing in the scope means nothing was owed, so zero.+ # nil when the scope has entries but no balance record covers them yet.+ def balance_record_on_or_before(date, scope)+ return Money.new(0, account.currency) if scope.none?- Money.new(amount_scope.sum(:amount), account.currency)+ amount = account.balances+ .where(currency: account.currency, date: ..date)+ .order(date: :desc)+ .pick(:end_balance)++ amount && Money.new(amount, account.currency)end- def summable_entries(window)- scoped = account.entries.excluding_pending.excluding_split_parents.where(date: window)+ # Payments made after the close settle the closed bill first, up to its+ # amount. Only the surplus, if any, reduces what was charged or adjusted in+ # the open cycle, so the figure is the debt still owed on that cycle (or a+ # credit when the surplus exceeds it).+ def accrued_after_bill_settlement(ledger)+ charges, adjustments = ledger.values_at(:charges, :adjustments)+ applied = payments_applied_to_open_cycle(ledger)+ return nil if charges.nil? || adjustments.nil? || applied.nil?- # An entry we cannot add up -- booked in another currency, or in none at- # all -- makes the total unknown rather than smaller. `where.not(currency:)`- # compiles to `!= AND IS NOT NULL`, so it never matches a NULL and the- # guard would sit there dead for the exact case it was written for. Compare- # the counts instead: anything outside the account's own currency refuses- # the whole statement, because quoting only the part that did match would- # report a partial figure as if it were the whole.- summable = scoped.where(currency: account.currency)- return nil if summable.count != scoped.count+ Money.new(charges.amount + adjustments.amount - applied.amount, charges.currency)+ end- summable+ # The part of the payments since the close that reduced the open cycle. The+ # payments settle the closed bill first, up to its amount, so only the+ # surplus is left for the open cycle. Without a known closed bill there is+ # nothing to settle first, so every payment counts against the open cycle.+ # Nil when the charges or payments cannot be totalled.+ def payments_applied_to_open_cycle(ledger)+ charges, credits, balance = ledger.values_at(:charges, :credits, :closed)+ return nil if charges.nil? || credits.nil?++ bill = balance ? [ balance.amount, 0 ].max : 0+ Money.new([ credits.amount.abs - bill, 0 ].max, charges.currency)end+ # What is still owed on the closed bill after payments since the close. A+ # closed balance that is itself a credit is kept as a credit, so the card+ # shows what the cardholder is owed rather than hiding it as zero.def statement_remaining(balance, credits)return nil if balance.nil? || credits.nil?- return Money.new(0, balance.currency) unless balance.positive?+ return balance unless balance.positive?Money.new([ balance.amount + credits.amount, 0 ].max, balance.currency)end@@ -230,7 +273,7 @@ class CreditCard < ApplicationRecord# it has passed, so the Overview still says it is overdue.def statement_due_date(last_due_date, remaining, as_of)return last_due_date if last_due_date.nil? || remaining.nil?- return last_due_date unless remaining.zero? && last_due_date < as_of+ return last_due_date if remaining.positive? || last_due_date >= as_ofpayment_due_date_for(next_statement_close_date(as_of: as_of))end@@ -284,12 +327,15 @@ class CreditCard < ApplicationRecordenddef statement_settled?(as_of: Date.current)- balance = last_statement_balance_money(as_of: as_of)+ last_close = last_statement_close_date(as_of: as_of)+ return false if last_close.nil?++ ledger = statement_ledger(as_of: as_of, last_close: last_close)+ balance = ledger[:closed]return false if balance.nil?return true unless balance.positive?- last_close = last_statement_close_date(as_of: as_of)- credits = sum_entries_in((last_close + 1)..as_of, amount_sign: :negative)+ credits = ledger[:credits]return false if credits.nil?credits.amount.abs >= balance.amountdiff --git a/app/views/credit_cards/tabs/_overview.html.erb b/app/views/credit_cards/tabs/_overview.html.erbindex d7a4f6e120..5fbd290ac2 100644--- a/app/views/credit_cards/tabs/_overview.html.erb+++ b/app/views/credit_cards/tabs/_overview.html.erb@@ -13,26 +13,22 @@<div class="@container"><div class="<%= summary_grid_class %>" data-testid="credit-card-summary-grid">- <%# The bill. This and the next card are a SPLIT of the balance in the page- header, not two more balances: the statement that closed is what you owe- now, and everything charged since belongs to the statement still- building. The two add back up to the debt, which is the one number the- header already gives; what the header cannot say is how much of it is- already a bill, and that is what this tab is for. %>+ <%# The bill. This card shows what is still owed on the statement that+ closed, after any payments made since it closed. The next card shows+ what has been charged or adjusted since then. Together they add back up+ to the current debt in the header. When the closed bill is a credit,+ this card shows that credit as a negative amount. %><%= summary_card title: t(".statement_balance") do %>- <%= summary.balance ? format_money(summary.balance) : t(".unknown") %>+ <%= summary.remaining ? format_money(summary.remaining) : t(".unknown") %><span class="mt-2 block space-y-1 text-sm text-secondary"><% if summary.due_date && due_for_last_balance %>- <span class="block">- <%= t(".due_on", date: l(summary.due_date, format: :long)) %>- </span>+ <% days_to_due = (summary.due_date - today).to_i %><span class="block <%= summary.status == :overdue ? "text-destructive" : "" %>">- <%= credit_card_due_countdown((summary.due_date - today).to_i) %>- </span>- <% end %>- <% if summary.remaining&.positive? && summary.balance && summary.remaining.amount < summary.balance.amount %>- <span class="block privacy-sensitive">- <%= t(".remaining_due", amount: format_money(summary.remaining)) %>+ <% if days_to_due.negative? %>+ <%= t(".due_overdue_days", date: l(summary.due_date, format: :long), count: days_to_due.abs) %>+ <% else %>+ <%= t(".due_on_days", date: l(summary.due_date, format: :long), count: days_to_due) %>+ <% end %></span><% end %><% if summary.status == :paid %>@@ -65,23 +61,38 @@<span class="mt-2 block space-y-1 text-sm text-secondary"><% if summary.accrued&.negative? %><span class="block"><%= t(".credit_toward_next") %></span>- <% elsif summary.due_date && !due_for_last_balance %>- <span class="block">- <%= t(".due_on", date: l(summary.due_date, format: :long)) %>- </span>- <span class="block"><%= credit_card_due_countdown((summary.due_date - today).to_i) %></span>- <% elsif summary.next_close %>- <span class="block"><%= t(".closes_on", date: l(summary.next_close, format: :long)) %></span>+ <% else %>+ <% if summary.due_date && !due_for_last_balance %>+ <span class="block">+ <%= t(".due_on_days", date: l(summary.due_date, format: :long), count: (summary.due_date - today).to_i) %>+ </span>+ <% end %>+ <% if summary.next_close %>+ <span class="block">+ <%= t(".closes_on_days", date: l(summary.next_close, format: :long), count: (summary.next_close - today).to_i) %>+ </span>+ <% end %><% end %>- <% if summary.charges && summary.credits %>+ <% if summary.charges && summary.payments_applied %><span class="flex items-center justify-between gap-4"><span><%= t(".charges") %></span><span class="font-medium text-primary privacy-sensitive"><%= format_money(summary.charges) %></span></span>- <span class="flex items-center justify-between gap-4">- <span><%= t(".payments_credits") %></span>- <span class="font-medium text-primary privacy-sensitive"><%= format_money(summary.credits.abs) %></span>- </span>+ <%# Only the payments that reduced these charges appear here. The part+ used to settle the closed bill is already on the card before this,+ so the lines above add up to the total. %>+ <% if summary.payments_applied.positive? %>+ <span class="flex items-center justify-between gap-4">+ <span><%= t(".payments_applied") %></span>+ <span class="font-medium text-primary privacy-sensitive"><%= format_money(summary.payments_applied) %></span>+ </span>+ <% end %>+ <% if summary.adjustments && !summary.adjustments.zero? %>+ <span class="flex items-center justify-between gap-4">+ <span><%= t(".balance_updates") %></span>+ <span class="font-medium text-primary privacy-sensitive"><%= format_money(summary.adjustments) %></span>+ </span>+ <% end %><% end %></span><% end %>@@ -119,7 +130,7 @@that explains nothing. Set against the statement balance above it answersthe question the cardholder actually has, which is whether paying theminimum clears the bill. %>- <% if card.minimum_payment_shortfall?(as_of: today) %>+ <% if card.minimum_payment_shortfall?(as_of: today, balance: summary.balance) %><div class="mt-2"><%= render DS::Alert.new(variant: :warning) do %><%= t(".above_minimum",diff --git a/config/locales/views/credit_cards/en.yml b/config/locales/views/credit_cards/en.ymlindex 06e6af1e05..4252873283 100644--- a/config/locales/views/credit_cards/en.yml+++ b/config/locales/views/credit_cards/en.yml@@ -56,16 +56,25 @@ en:annual_percentage_rate: Annual Percentage Rateapr: APRbalance_carried_label: Balance carried+ balance_updates: Balance updatescharges: Chargesestimated_interest_label: Estimated interestmonthly_rate_label: Monthly rateper_month: "%{amount}/month"- closes_on: Next statement closes %{date}+ closes_on_days:+ zero: Statement closes %{date} (today)+ one: Statement closes %{date} (1 day)+ other: Statement closes %{date} (%{count} days)+ due_overdue_days:+ one: Due %{date} (1 day overdue)+ other: Due %{date} (%{count} days overdue)+ due_on_days:+ zero: Due %{date} (today)+ one: Due %{date} (1 day)+ other: Due %{date} (%{count} days)credit_toward_next: Credit toward the next statement- due_on: "Due %{date}"edit_card_details: Edit card details- payments_credits: Payments/Credits- remaining_due: Remaining due %{amount}+ payments_applied: Payments appliedscheduled_payment: Scheduled payment %{amount} on %{date}since_last_statement: Since Last Statementstatement_balance: Statement Balancediff --git a/test/controllers/accounts_controller_test.rb b/test/controllers/accounts_controller_test.rbindex 2c59c4150b..cb90728220 100644--- a/test/controllers/accounts_controller_test.rb+++ b/test/controllers/accounts_controller_test.rb@@ -989,6 +989,7 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestentryable: Transaction.new)+ materialize_balances(accounts(:credit_card))get account_url(accounts(:credit_card), tab: "overview")assert_response :success@@ -999,6 +1000,7 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestsign_in users(:family_admin)accounts(:credit_card).credit_card.update!(statement_close_day: 25, due_day: 5, apr: nil, minimum_payment: nil)+ materialize_balances(accounts(:credit_card))get account_url(accounts(:credit_card), tab: "overview")assert_response :success@@ -1011,6 +1013,7 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestsign_in users(:family_admin)accounts(:credit_card).credit_card.update!(statement_close_day: 25, due_day: 5, apr: 18.99, minimum_payment: nil)+ materialize_balances(accounts(:credit_card))get account_url(accounts(:credit_card), tab: "overview")assert_response :success@@ -1030,6 +1033,7 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestentryable: Transaction.new)+ materialize_balances(account)get account_url(account, tab: "overview")assert_response :success@@ -1052,6 +1056,7 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestentryable: Transaction.new)+ materialize_balances(account)get account_url(account, tab: "overview")assert_response :success@@ -1074,10 +1079,16 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestentryable: Transaction.new)+ materialize_balances(account)get account_url(account, tab: "overview")assert_response :success- assert_match I18n.t("credit_cards.tabs.overview.remaining_due", amount: Money.new(60, "USD").format), response.body+ # The bill card shows what is still owed on the statement: 100 less the 40 paid.+ # Scoped to that card, since the APR card also renders a balance.+ bill_card = Nokogiri::HTML(response.body)+ .css("[data-testid=credit-card-summary-grid] > div:first-child")+ .first+ assert_includes bill_card.text, Money.new(60, "USD").formatassert_match I18n.t("credit_cards.tabs.overview.status_partial"), response.bodyendend@@ -1097,14 +1108,15 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestentryable: Transaction.new)+ materialize_balances(account)get account_url(account, tab: "overview")assert_response :successassert_match I18n.t("credit_cards.tabs.overview.charges"), response.body- assert_match I18n.t("credit_cards.tabs.overview.payments_credits"), response.body+ assert_match I18n.t("credit_cards.tabs.overview.payments_applied"), response.bodyassert_match Money.new(100, "USD").format, response.bodyassert_match Money.new(40, "USD").format, response.body- assert_match I18n.t("credit_cards.tabs.overview.closes_on", date: I18n.l(Date.new(2026, 11, 10), format: :long)), response.body+ assert_match I18n.t("credit_cards.tabs.overview.closes_on_days", date: I18n.l(Date.new(2026, 11, 10), format: :long), count: 25), response.bodyendend@@ -1127,6 +1139,7 @@ class AccountsControllerTest < ActionDispatch::IntegrationTest)open_due = series.recurring_occurrences.open_status.minimum(:due_on)+ materialize_balances(account)get account_url(account, tab: "overview")assert_response :success@@ -1155,6 +1168,7 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestmanual: true)+ materialize_balances(account)get account_url(account, tab: "overview")assert_response :success@@ -1172,10 +1186,11 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestentryable: Transaction.new)+ materialize_balances(account)get account_url(account, tab: "overview")assert_response :success- assert_select "span.text-destructive", text: I18n.t("credit_cards.due.overdue", count: 9)+ assert_select "span.text-destructive", text: I18n.t("credit_cards.tabs.overview.due_overdue_days", date: I18n.l(Date.new(2026, 10, 21), format: :long), count: 9)endend@@ -1188,11 +1203,12 @@ class AccountsControllerTest < ActionDispatch::IntegrationTest# of THIS month -- not the 26th of next, which is the statement still# building and not yet owed.travel_to Date.new(2026, 10, 16) do+ materialize_balances(accounts(:credit_card))get account_url(accounts(:credit_card), tab: "overview")assert_response :successassert_match I18n.l(Date.new(2026, 10, 26), format: :long), response.body- assert_match I18n.t("credit_cards.due.in_days", count: 10), response.body+ assert_match I18n.t("credit_cards.tabs.overview.due_on_days", date: I18n.l(Date.new(2026, 10, 26), format: :long), count: 10), response.bodyendend@@ -1211,6 +1227,7 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestentryable: Transaction.new)+ materialize_balances(account)get account_url(account, tab: "overview")assert_response :success@@ -1237,6 +1254,7 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestentryable: Transaction.new)+ materialize_balances(account)get account_url(account, tab: "overview")assert_response :success@@ -1248,6 +1266,7 @@ class AccountsControllerTest < ActionDispatch::IntegrationTesttest "credit card overview asks for a cycle when none is set" dosign_in users(:family_admin)+ materialize_balances(accounts(:credit_card))get account_url(accounts(:credit_card), tab: "overview")assert_response :success@@ -2018,6 +2037,12 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestAccount::LogoFetcher::Icon.new(key:, source:, name:, body:, size:, content_type: "image/png", extension: "png")end+ # The Overview reads the account's balance records, which sync builds from+ # the entries. Tests build them after creating entries directly.+ def materialize_balances(account)+ Balance::Materializer.new(account, strategy: :forward).materialize_balances+ end+# Lucide SVGs carry no icon-name class, so an icon is identified by its path data.def eye_off_icon_pathsNokogiri::HTML::DocumentFragment.parse(ApplicationController.helpers.icon("eye-off")).css("path").map { |path| path["d"] }diff --git a/test/models/credit_card_test.rb b/test/models/credit_card_test.rbindex f9dddb44b3..cce590043a 100644--- a/test/models/credit_card_test.rb+++ b/test/models/credit_card_test.rb@@ -288,9 +288,30 @@ class CreditCardTest < ActiveSupport::TestCase)end+ materialize_balances(account)assert_equal 400, card.last_statement_balance_money(as_of: as_of).amountend+ test "a balance update after an unknown closed balance does not invent an adjustment from mixed currencies" do+ card = statement_card(close_day: 25, due_day: 5)+ account = card.account+ as_of = Date.new(2026, 10, 16)++ account.entries.create!(+ name: "Foreign charge before close", date: Date.new(2026, 9, 11), amount: 100,+ currency: "EUR", entryable: Transaction.new+ )+ charge(account, Date.new(2026, 10, 1), 50)+ balance_update(account, Date.new(2026, 10, 10), 200)++ summary = card.statement_summary(as_of: as_of, viewer: users(:family_admin))++ assert_nil summary.balance+ assert_equal 50, summary.charges.amount+ assert_equal 0, summary.adjustments.amount+ assert_equal 50, summary.accrued.amount+ end+test "a card with entries in another currency reports no statement rather than a wrong one" docard = statement_card(close_day: 25, due_day: 5)account = card.account@@ -308,6 +329,7 @@ class CreditCardTest < ActiveSupport::TestCaseassert_equal 0, card.accrued_since_last_close_money(as_of: Date.new(2026, 10, 16)).amountforeign.destroy!+ materialize_balances(account)assert_equal 100, card.last_statement_balance_money(as_of: Date.new(2026, 10, 16)).amountend@@ -348,6 +370,77 @@ class CreditCardTest < ActiveSupport::TestCaseassert_not card.minimum_payment_shortfall?end+ test "a balance update before the close replaces the running total instead of adding to it" do+ card = statement_card(close_day: 16, due_day: 6)+ account = card.account+ as_of = Date.new(2026, 10, 16)++ balance_update(account, Date.new(2025, 1, 1), 200)+ charge(account, Date.new(2026, 9, 1), 600)+ balance_update(account, Date.new(2026, 10, 1), 800)++ # The 800 already includes the 600 charged, so counting both would show+ # 1,400 against a debt of 800.+ assert_equal 800, card.last_statement_balance_money(as_of: as_of).amount+ assert_equal 0, card.accrued_since_last_close_money(as_of: as_of).amount+ end++ test "a balance update inside the open cycle is its own adjustment, not a second copy of the charges" do+ card = statement_card(close_day: 16, due_day: 6)+ account = card.account+ as_of = Date.new(2026, 10, 30)++ charge(account, Date.new(2026, 10, 1), 800)+ charge(account, Date.new(2026, 10, 20), 100)+ balance_update(account, Date.new(2026, 10, 25), 1_000)++ summary = card.statement_summary(as_of: as_of, viewer: users(:family_admin))++ assert_equal 800, summary.balance.amount+ assert_equal 800, summary.remaining.amount+ assert_equal 100, summary.charges.amount+ assert_equal 0, summary.credits.amount+ assert_equal 100, summary.adjustments.amount+ assert_equal 200, summary.accrued.amount+ assert_equal 1_000, summary.remaining.amount + summary.accrued.amount+ end++ test "a balance update and a payment inside the open cycle still add up to the debt" do+ card = statement_card(close_day: 16, due_day: 6)+ account = card.account+ as_of = Date.new(2026, 10, 30)++ charge(account, Date.new(2026, 10, 1), 800)+ charge(account, Date.new(2026, 10, 20), 300)+ balance_update(account, Date.new(2026, 10, 25), 1_000)+ charge(account, Date.new(2026, 10, 28), -200)++ summary = card.statement_summary(as_of: as_of, viewer: users(:family_admin))++ # The update drops the open cycle by 100 against what was charged. The+ # payment settles the closed bill first, so none of it reduces the open cycle.+ assert_equal 800, summary.balance.amount+ assert_equal 600, summary.remaining.amount+ assert_equal 300, summary.charges.amount+ assert_equal(-200, summary.credits.amount)+ assert_equal(-100, summary.adjustments.amount)+ assert_equal 200, summary.accrued.amount+ assert_equal 800, summary.remaining.amount + summary.accrued.amount+ end++ test "an opening anchor and reconciliations before the close do not inflate the closed statement" do+ card = statement_card(close_day: 16, due_day: 6)+ account = card.account+ as_of = Date.new(2026, 10, 16)++ balance_update(account, Date.new(2024, 4, 16), 100)+ charge(account, Date.new(2026, 9, 1), 2_789.51)+ balance_update(account, Date.new(2026, 10, 12), 2_892.54)++ assert_equal BigDecimal("2892.54"), card.last_statement_balance_money(as_of: as_of).amount+ assert_equal 0, card.accrued_since_last_close_money(as_of: as_of).amount+ end+test "the statement summary reports the remaining amount and partial status" docard = statement_card(close_day: 10, due_day: 26)charge(card.account, Date.new(2026, 9, 20), 300)@@ -359,12 +452,40 @@ class CreditCardTest < ActiveSupport::TestCaseassert_equal 200, summary.remaining.amountassert_equal 0, summary.charges.amountassert_equal(-100, summary.credits.amount)- assert_equal(-100, summary.accrued.amount)+ # The payment settles part of the closed bill, not the open cycle.+ assert_equal 0, summary.accrued.amountassert_equal Date.new(2026, 10, 26), summary.due_dateassert_equal Date.new(2026, 10, 26), summary.last_due_dateassert_equal :partial, summary.statusend+ test "post-close payments settle the closed bill first and only the surplus reduces new charges" do+ card = statement_card(close_day: 16, due_day: 6)+ charge(card.account, Date.new(2026, 10, 1), 800)+ charge(card.account, Date.new(2026, 10, 20), 300)+ charge(card.account, Date.new(2026, 10, 25), -1000)++ summary = card.statement_summary(as_of: Date.new(2026, 10, 30), viewer: users(:family_admin))++ assert_equal 800, summary.balance.amount+ assert_equal 0, summary.remaining.amount+ assert_equal :paid, summary.status+ assert_equal 100, summary.accrued.amount+ assert_equal 100, card.accrued_since_last_close_money(as_of: Date.new(2026, 10, 30)).amount+ end++ test "the payments applied line is only the surplus that reduced the open cycle" do+ card = statement_card(close_day: 16, due_day: 6)+ charge(card.account, Date.new(2026, 10, 1), 800)+ charge(card.account, Date.new(2026, 10, 20), 300)+ charge(card.account, Date.new(2026, 10, 25), -1000)++ summary = card.statement_summary(as_of: Date.new(2026, 10, 30), viewer: users(:family_admin))++ assert_equal 200, summary.payments_applied.amount+ assert_equal 100, summary.accrued.amount+ end+test "the statement summary marks a settled statement as paid and moves to the next due date" docard = statement_card(close_day: 10, due_day: 26)charge(card.account, Date.new(2026, 9, 20), 300)@@ -389,6 +510,18 @@ class CreditCardTest < ActiveSupport::TestCaseassert_equal Date.new(2026, 10, 26), summary.due_dateend+ test "a closed statement that is a credit stays a credit rather than being shown as zero" do+ card = statement_card(close_day: 10, due_day: 26)+ charge(card.account, Date.new(2026, 9, 20), -100)++ summary = card.statement_summary(as_of: Date.new(2026, 10, 16), viewer: users(:family_admin))++ assert_equal(-100, summary.balance.amount)+ assert_equal(-100, summary.remaining.amount)+ assert_equal 0, summary.accrued.amount+ assert_equal :no_balance, summary.status+ end+test "the statement summary reports no balance when the statement is zero" docard = statement_card(close_day: 10, due_day: 26)@@ -533,15 +666,37 @@ class CreditCardTest < ActiveSupport::TestCaseseries.reloadend+ # A balance update states what is owed on that date, as a reconciliation+ # or the opening balance does.+ def balance_update(account, date, balance)+ entry = account.entries.create!(+ name: "Balance update",+ date: date,+ amount: balance,+ currency: account.currency,+ entryable: Valuation.new(kind: "reconciliation")+ )+ materialize_balances(account)+ entry+ end+# Positive amount is a charge on a liability; negative is a payment, which# is how ForwardCalculator reads a card's entries.def charge(account, date, amount)- account.entries.create!(+ entry = account.entries.create!(name: "Statement test entry",date: date,amount: amount,currency: account.currency,entryable: Transaction.new)+ materialize_balances(account)+ entry+ end++ # The statement reads the account's balance records, which sync builds from+ # the entries. Tests build them the same way after changing the entries.+ def materialize_balances(account)+ Balance::Materializer.new(account, strategy: :forward).materialize_balancesendend