Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add credit card statement cycle support (#4270)

Shibu M05047f61cd1e
diff --git a/app/components/UI/account_page.rb b/app/components/UI/account_page.rb
index 1469450c9b..e34eb5f569 100644
--- a/app/components/UI/account_page.rb
+++ b/app/components/UI/account_page.rb
@@ -57,6 +57,8 @@ class UI::AccountPage < ApplicationComponent
[ :activity, :holdings ]
when "Loan"
account.loan.amortizable? ? [ :activity, :overview, :schedule ] : [ :activity, :overview ]
+ when "CreditCard"
+ [ :activity, :overview ]
when "Property", "Vehicle"
[ :activity, :overview ]
else
@@ -95,14 +97,14 @@ class UI::AccountPage < ApplicationComponent
activity_feed
when :overview
# Accountable is responsible for implementing the partial in the correct
- # folder. The loan's tab shows date-sensitive figures and takes the
- # page's one reference date, like its Schedule tab.
+ # folder. These tabs show date-sensitive figures and take the page's one
+ # reference date, like the Schedule tab does.
locals = { account: account }
- locals[:as_of] = as_of if account.accountable_type == "Loan"
- render "#{account.accountable_type.downcase.pluralize}/tabs/#{tab}", **locals
+ locals[:as_of] = as_of if %w[Loan CreditCard].include?(account.accountable_type)
+ render "#{accountable_view_folder}/tabs/#{tab}", **locals
when :holdings
# Accountable is responsible for implementing the partial in the correct folder
- render "#{account.accountable_type.downcase.pluralize}/tabs/#{tab}", account: account
+ render "#{accountable_view_folder}/tabs/#{tab}", account: account
when :schedule
render "loans/tabs/schedule", account: account, as_of: as_of, projection: loan_projection
when :statements
@@ -133,4 +135,15 @@ class UI::AccountPage < ApplicationComponent
can_manage_statements: can_manage_statements
}
end
+
+ private
+ # The app/views folder an accountable's own tab partials live in.
+ #
+ # Not `accountable_type.downcase.pluralize`, which reads a two-word class
+ # name as one word: "CreditCard" became `creditcards/tabs/overview` and
+ # there is no such folder. The accountable names its own folder, and a
+ # multi-word one is underscored.
+ def accountable_view_folder
+ account.accountable_type.underscore.pluralize
+ end
end
diff --git a/app/controllers/credit_cards_controller.rb b/app/controllers/credit_cards_controller.rb
index cde48706a7..81b57feb3d 100644
--- a/app/controllers/credit_cards_controller.rb
+++ b/app/controllers/credit_cards_controller.rb
@@ -7,7 +7,9 @@ class CreditCardsController < ApplicationController
:minimum_payment,
:apr,
:annual_fee,
- :expiration_date
+ :expiration_date,
+ :statement_close_day,
+ :due_day
)
def update
diff --git a/app/helpers/credit_cards_helper.rb b/app/helpers/credit_cards_helper.rb
new file mode 100644
index 0000000000..1b96d7a99e
--- /dev/null
+++ b/app/helpers/credit_cards_helper.rb
@@ -0,0 +1,12 @@
+module CreditCardsHelper
+ def credit_card_day_of_month_options
+ (1..31).map { |day| [ localized_ordinal(day), day ] }
+ end
+
+ def credit_card_due_countdown(days)
+ return nil if days.nil?
+ return t("credit_cards.due.overdue", count: days.abs) if days.negative?
+
+ t("credit_cards.due.in_days", count: days)
+ end
+end
diff --git a/app/models/credit_card.rb b/app/models/credit_card.rb
index 6d1f9824bc..423eb72ec2 100644
--- a/app/models/credit_card.rb
+++ b/app/models/credit_card.rb
@@ -7,6 +7,10 @@ class CreditCard < ApplicationRecord
"credit_card" => { short: "Credit Card", long: "Credit Card" }
}.freeze
+ validates :statement_close_day, :due_day,
+ numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 31 },
+ allow_nil: true
+
class << self
def color
"#F13636"
@@ -44,4 +48,117 @@ class CreditCard < ApplicationRecord
def annual_fee_money
annual_fee ? Money.new(annual_fee, account.currency) : nil
end
+
+ def statement_cycle_configured?
+ statement_close_day.present? && account.present?
+ end
+
+ def last_statement_close_date(as_of: Date.current)
+ return nil unless statement_cycle_configured?
+
+ close = day_of_month_in(as_of, statement_close_day)
+ return close if close <= as_of
+
+ day_of_month_in(as_of.prev_month, statement_close_day)
+ end
+
+ def previous_statement_close_date(as_of: Date.current)
+ last_close = last_statement_close_date(as_of: as_of)
+ return nil if last_close.nil?
+
+ day_of_month_in(last_close.prev_month, statement_close_day)
+ end
+
+ def next_statement_close_date(as_of: Date.current)
+ last_close = last_statement_close_date(as_of: as_of)
+ return nil if last_close.nil?
+
+ day_of_month_in(last_close.next_month, statement_close_day)
+ end
+
+ def payment_due_date_for(close_date)
+ return nil if close_date.nil? || due_day.blank?
+
+ due = day_of_month_in(close_date, due_day)
+ due = day_of_month_in(close_date.next_month, due_day) if statement_close_day.present? && due_day < statement_close_day
+
+ due
+ end
+
+ def next_payment_due_date(as_of: Date.current)
+ last_close = last_statement_close_date(as_of: as_of)
+ return nil if last_close.nil?
+
+ due = payment_due_date_for(last_close)
+ return nil if due.nil?
+
+ # Give way only once the statement is paid; an unpaid bill stays overdue.
+ due = payment_due_date_for(next_statement_close_date(as_of: as_of)) if due < as_of && statement_settled?(as_of: as_of)
+
+ due
+ end
+
+ def days_until_due(as_of: Date.current)
+ due = next_payment_due_date(as_of: as_of)
+ return nil if due.nil?
+
+ (due - as_of).to_i
+ end
+
+ def last_statement_balance_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)
+ end
+
+ def 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)
+ end
+
+ def minimum_payment_shortfall?(as_of: Date.current)
+ minimum = minimum_payment_money
+ balance = last_statement_balance_money(as_of: as_of)
+ return false if minimum.nil? || balance.nil?
+
+ balance > minimum
+ end
+
+ private
+ def sum_entries_in(window)
+ scoped = account.entries.excluding_pending.excluding_split_parents.where(date: window)
+
+ # 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(summable.sum(:amount), account.currency)
+ end
+
+ def statement_settled?(as_of: Date.current)
+ balance = last_statement_balance_money(as_of: as_of)
+ return false if balance.nil?
+ return true unless balance.positive?
+
+ last_close = last_statement_close_date(as_of: as_of)
+ payments = account.entries.excluding_pending.excluding_split_parents
+ .where(date: (last_close + 1)..as_of, currency: account.currency)
+ .where("amount < 0")
+ .sum(:amount).abs
+
+ payments >= balance.amount
+ end
+
+ def day_of_month_in(base_date, day)
+ Date.new(base_date.year, base_date.month, [ day, base_date.end_of_month.day ].min)
+ end
end
diff --git a/app/models/plaid_account/liabilities/credit_processor.rb b/app/models/plaid_account/liabilities/credit_processor.rb
index 7a5b216dbb..e435275bcd 100644
--- a/app/models/plaid_account/liabilities/credit_processor.rb
+++ b/app/models/plaid_account/liabilities/credit_processor.rb
@@ -10,7 +10,7 @@ class PlaidAccount::Liabilities::CreditProcessor
attributes: {
minimum_payment: credit_data.dig("minimum_payment_amount"),
apr: credit_data.dig("aprs", 0, "apr_percentage")
- },
+ }.merge(statement_cycle_attributes),
source: "plaid"
)
end
@@ -29,4 +29,21 @@ class PlaidAccount::Liabilities::CreditProcessor
def credit_data
plaid_account.raw_liabilities_payload["credit"]
end
+
+ def statement_cycle_attributes
+ {
+ statement_close_day: day_of_month(credit_data["last_statement_issue_date"]),
+ due_day: day_of_month(credit_data["next_payment_due_date"])
+ }.select { |attribute, day| day.present? && account.accountable.public_send(attribute).blank? }
+ end
+
+ def day_of_month(raw_date)
+ return nil if raw_date.blank?
+
+ Date.parse(raw_date.to_s).day
+ rescue Date::Error
+ # An unparseable date is no reason to fail a sync over: everything else
+ # in the payload is still worth taking.
+ nil
+ end
end
diff --git a/app/views/credit_cards/_form.html.erb b/app/views/credit_cards/_form.html.erb
index 40655cc391..f9fb8d626e 100644
--- a/app/views/credit_cards/_form.html.erb
+++ b/app/views/credit_cards/_form.html.erb
@@ -33,6 +33,29 @@
placeholder: t("credit_cards.form.annual_fee_placeholder"),
min: 0 %>
</div>
+
+ <%# The two days that make up the statement cycle. Only the close day is
+ load-bearing -- without it there is no telling which charge belongs to
+ which statement -- so the due day is allowed to stand on its own for a
+ card whose close day came from a provider. %>
+ <div class="space-y-1">
+ <div class="flex items-center gap-2">
+ <%= credit_card_form.select :statement_close_day,
+ options_for_select(
+ credit_card_day_of_month_options,
+ credit_card_form.object.statement_close_day
+ ),
+ { include_blank: true, label: t("credit_cards.form.statement_close_day") } %>
+
+ <%= credit_card_form.select :due_day,
+ options_for_select(
+ credit_card_day_of_month_options,
+ credit_card_form.object.due_day
+ ),
+ { include_blank: true, label: t("credit_cards.form.due_day") } %>
+ </div>
+ <p class="text-secondary text-xs"><%= t("credit_cards.form.statement_cycle_description") %></p>
+ </div>
<% end %>
<% enable_banking_account = account.provider_account_for("EnableBankingAccount") if account.persisted? %>
diff --git a/app/views/credit_cards/tabs/_overview.html.erb b/app/views/credit_cards/tabs/_overview.html.erb
new file mode 100644
index 0000000000..6db97959ce
--- /dev/null
+++ b/app/views/credit_cards/tabs/_overview.html.erb
@@ -0,0 +1,118 @@
+<%# locals: (account:, as_of: Date.current) %>
+
+<%# ONE reference date for every figure on this tab, the same one the Loan tab
+ takes, so a page read at the edge of a statement close does not show two
+ different cycles on two tabs. %>
+<% today = as_of %>
+<% card = account.credit_card %>
+
+<% if card.statement_cycle_configured? %>
+ <% last_balance = card.last_statement_balance_money(as_of: today) %>
+ <% accrued = card.accrued_since_last_close_money(as_of: today) %>
+ <% due_date = card.next_payment_due_date(as_of: today) %>
+ <% last_due_date = card.payment_due_date_for(card.last_statement_close_date(as_of: today)) %>
+ <% due_for_last_balance = due_date.present? && due_date == last_due_date %>
+ <% next_close = card.next_statement_close_date(as_of: today) %>
+
+ <div class="grid grid-cols-3 gap-2">
+ <%# 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 due date sits under the amount rather than in a card of its own,
+ because a bare date beside a balance reads as a second, separate bill. %>
+ <%= summary_card title: t(".statement_balance") do %>
+ <%= last_balance ? format_money(last_balance) : t(".unknown") %>
+ <% if due_date && due_for_last_balance %>
+ <span class="block text-sm text-secondary">
+ <%= t(".due_on", date: l(due_date, format: :long)) %>
+ </span>
+ <span class="block text-sm text-secondary"><%= credit_card_due_countdown(card.days_until_due(as_of: today)) %></span>
+ <% end %>
+ <% end %>
+
+ <%# A negative figure here is not a nonsense balance: paying the card down
+ by more than has been charged since the close leaves a credit that
+ reduces the next statement. Labelling it as such keeps the two cards
+ summing to the debt in the header instead of appearing to contradict it.
+
+ The credit is checked before the due date rather than after it. A due
+ date that has already rolled past the last statement belongs to the
+ statement still building, and when the cardholder holds a credit that
+ statement may not produce a bill at all -- quoting a due date there
+ would promise a payment the credit may well cancel. %>
+ <%= summary_card title: t(".since_last_statement") do %>
+ <%= accrued ? format_money(accrued) : t(".unknown") %>
+ <% if accrued&.negative? %>
+ <span class="block text-sm text-secondary"><%= t(".credit_toward_next") %></span>
+ <% elsif due_date && !due_for_last_balance %>
+ <span class="block text-sm text-secondary">
+ <%= t(".due_on", date: l(due_date, format: :long)) %>
+ </span>
+ <span class="block text-sm text-secondary"><%= credit_card_due_countdown(card.days_until_due(as_of: today)) %></span>
+ <% elsif next_close %>
+ <span class="block text-sm text-secondary"><%= t(".closes_on", date: l(next_close, format: :long)) %></span>
+ <% end %>
+ <% end %>
+
+ <%= summary_card title: t(".apr") do %>
+ <%= card.apr.present? ? number_to_percentage(card.apr, precision: 3) : t(".unknown") %>
+ <% end %>
+ </div>
+
+ <%# The minimum payment earns its place here only as this comparison. On its
+ own it is a number with nothing to be read against: a minimum is a share
+ of whatever the statement came to, so "Minimum Payment $100" beside a
+ balance the user cannot check it against is the one figure on this tab
+ that explains nothing. Set against the statement balance above it answers
+ the question the cardholder actually has, which is whether paying the
+ minimum clears the bill. %>
+ <% if card.minimum_payment_shortfall?(as_of: today) %>
+ <div class="mt-2">
+ <%= render DS::Alert.new(variant: :warning) do %>
+ <%= t(".above_minimum",
+ balance: format_money(last_balance),
+ minimum: format_money(card.minimum_payment_money)) %>
+ <% end %>
+ </div>
+ <% end %>
+
+ <%# A card whose cycle is configured but whose statement totals unknown is
+ saying something different from one that totals zero: the first has
+ entries we cannot add up in the card's own currency. Quoting $0.00 there
+ would be a wrong number presented as a right one. %>
+ <% if accrued.nil? || last_balance.nil? %>
+ <div class="mt-2">
+ <%= render DS::Alert.new(variant: :info) do %>
+ <%= t(".multi_currency_unavailable") %>
+ <% end %>
+ </div>
+ <% end %>
+
+ <div class="flex justify-center py-8">
+ <%= render DS::Link.new(
+ text: t(".edit_card_details"),
+ variant: "ghost",
+ href: edit_credit_card_path(account),
+ frame: :modal
+ ) %>
+ </div>
+<% else %>
+ <%= render DS::EmptyState.new(
+ icon: "calendar",
+ title: t(".no_cycle_title"),
+ description: t(".no_cycle_description")
+ ) %>
+
+ <div class="flex justify-center pb-8">
+ <%= render DS::Link.new(
+ text: t(".edit_card_details"),
+ variant: "secondary",
+ href: edit_credit_card_path(account),
+ frame: :modal
+ ) %>
+ </div>
+<% end %>
diff --git a/config/locales/views/credit_cards/en.yml b/config/locales/views/credit_cards/en.yml
index 3dac2de089..791dd867d0 100644
--- a/config/locales/views/credit_cards/en.yml
+++ b/config/locales/views/credit_cards/en.yml
@@ -1,6 +1,14 @@
---
en:
credit_cards:
+ due:
+ in_days:
+ zero: Due today
+ one: Due tomorrow
+ other: Due in %{count} days
+ overdue:
+ one: Due yesterday
+ other: "%{count} days overdue"
edit:
edit: Edit %{account}
form:
@@ -10,9 +18,16 @@ en:
apr_placeholder: '15.99'
available_credit: Available credit
available_credit_placeholder: '10000'
+ due_day: Payment due day
expiration_date: Expiration date
minimum_payment: Minimum payment
minimum_payment_placeholder: '100'
+ statement_close_day: Statement closes on
+ statement_cycle_description: The day of the month your statement closes and
+ the day the payment is due. With these set, the Overview tab shows what
+ your last statement came to and what is building toward the next one.
+ A linked card fills these in automatically and keeps what you set by
+ hand.
sophtron_balance_sign_auto: Automatic
sophtron_balance_sign_credit: Credit (bank owes you)
sophtron_balance_sign_debt: Debt (you owe the bank)
@@ -32,6 +47,26 @@ en:
bank, or from the Available credit field if your bank does not provide
one.
treat_balance_as_available_credit_label: Balance is available credit
+ tabs:
+ overview:
+ above_minimum: This statement came to %{balance}, above the %{minimum} minimum.
+ Paying only the minimum leaves the balance on the card at this APR.
+ apr: APR
+ closes_on: Next statement closes %{date}
+ credit_toward_next: Credit toward the next statement
+ due_on: "Due %{date}"
+ edit_card_details: Edit card details
+ since_last_statement: Since Last Statement
+ statement_balance: Statement Balance
+ multi_currency_unavailable: This statement adds up entries recorded in more
+ than one currency, which cannot be totalled here without a rate for every
+ one of them. The balances are left blank rather than guessed.
+ no_cycle_description: Set the day your statement closes and the day payment
+ is due, and this tab will show what your last statement came to and what
+ is building toward the next one. A linked card usually fills these in for
+ you.
+ no_cycle_title: No statement cycle set
+ unknown: Unknown
new:
title: Enter credit card details
update:
diff --git a/db/migrate/20261012120000_add_statement_cycle_to_credit_cards.rb b/db/migrate/20261012120000_add_statement_cycle_to_credit_cards.rb
new file mode 100644
index 0000000000..255fa6b434
--- /dev/null
+++ b/db/migrate/20261012120000_add_statement_cycle_to_credit_cards.rb
@@ -0,0 +1,13 @@
+class AddStatementCycleToCreditCards < ActiveRecord::Migration[8.1]
+ def change
+ add_column :credit_cards, :statement_close_day, :integer
+ add_column :credit_cards, :due_day, :integer
+
+ add_check_constraint :credit_cards,
+ "statement_close_day BETWEEN 1 AND 31",
+ name: "chk_credit_cards_statement_close_day"
+ add_check_constraint :credit_cards,
+ "due_day BETWEEN 1 AND 31",
+ name: "chk_credit_cards_due_day"
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 7ee2f17aad..55d4b3e361 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -574,11 +574,15 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_20_090001) do
t.decimal "apr", precision: 10, scale: 2
t.decimal "available_credit", precision: 10, scale: 2
t.datetime "created_at", null: false
+ t.integer "due_day"
t.date "expiration_date"
t.jsonb "locked_attributes", default: {}
t.decimal "minimum_payment", precision: 10, scale: 2
+ t.integer "statement_close_day"
t.string "subtype"
t.datetime "updated_at", null: false
+ t.check_constraint "due_day >= 1 AND due_day <= 31", name: "chk_credit_cards_due_day"
+ t.check_constraint "statement_close_day >= 1 AND statement_close_day <= 31", name: "chk_credit_cards_statement_close_day"
end
create_table "cryptos", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
diff --git a/test/controllers/accounts_controller_test.rb b/test/controllers/accounts_controller_test.rb
index a4916c0799..385edc4df2 100644
--- a/test/controllers/accounts_controller_test.rb
+++ b/test/controllers/accounts_controller_test.rb
@@ -776,6 +776,109 @@ class AccountsControllerTest < ActionDispatch::IntegrationTest
assert_select "input[type=file]", count: 0
end
+ test "credit card page offers an overview tab" do
+ sign_in users(:family_admin)
+
+ get account_url(accounts(:credit_card))
+
+ assert_response :success
+ assert_select "[role=tab][data-id=overview]"
+ assert_select "[role=tabpanel][data-id=overview]"
+ end
+
+ test "credit card overview renders the statement cycle" do
+ sign_in users(:family_admin)
+ card = accounts(:credit_card).credit_card
+ card.update!(statement_close_day: 25, due_day: 5, minimum_payment: 25)
+ accounts(:credit_card).entries.create!(
+ name: "Cycle charge",
+ date: Date.current.beginning_of_month + 9.days,
+ amount: 100,
+ currency: "USD",
+ entryable: Transaction.new
+ )
+
+ get account_url(accounts(:credit_card), tab: "overview")
+
+ assert_response :success
+ assert_match I18n.t("credit_cards.tabs.overview.statement_balance"), response.body
+ end
+
+ test "credit card overview shows the payment due this month for an early close day" do
+ sign_in users(:family_admin)
+ accounts(:credit_card).credit_card.update!(statement_close_day: 10, due_day: 26)
+
+ # A card closing on the 10th and due on the 26th, read on the 16th. The
+ # bill due is the statement that closed on the 10th, which falls on the 26th
+ # 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
+ get account_url(accounts(:credit_card), tab: "overview")
+
+ assert_response :success
+ assert_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
+ end
+ end
+
+ test "credit card overview reads a negative since-statement balance as a credit" do
+ sign_in users(:family_admin)
+ account = accounts(:credit_card)
+ account.credit_card.update!(statement_close_day: 10, due_day: 26)
+
+ travel_to Date.new(2026, 10, 16) do
+ account.entries.create!(
+ name: "Cycle charge", date: Date.new(2026, 9, 20), amount: 100, currency: "USD",
+ entryable: Transaction.new
+ )
+ account.entries.create!(
+ name: "Payment after the close", date: Date.new(2026, 10, 12), amount: -250, currency: "USD",
+ entryable: Transaction.new
+ )
+
+ get account_url(account, tab: "overview")
+
+ assert_response :success
+ assert_match I18n.t("credit_cards.tabs.overview.credit_toward_next"), response.body
+ end
+ end
+
+ test "credit card overview shows the credit label when a credit outlives the due date" do
+ sign_in users(:family_admin)
+ account = accounts(:credit_card)
+ account.credit_card.update!(statement_close_day: 10, due_day: 26)
+
+ # Read after the 26th: the due date has rolled to the statement still
+ # building, and the cardholder has paid down more than that statement has
+ # accrued. The credit is the fact worth stating; a due date here would
+ # promise a payment the credit may cancel.
+ travel_to Date.new(2026, 10, 30) do
+ account.entries.create!(
+ name: "Cycle charge", date: Date.new(2026, 9, 20), amount: 100, currency: "USD",
+ entryable: Transaction.new
+ )
+ account.entries.create!(
+ name: "Payment after the close", date: Date.new(2026, 10, 12), amount: -250, currency: "USD",
+ entryable: Transaction.new
+ )
+
+ get account_url(account, tab: "overview")
+
+ assert_response :success
+ assert_match I18n.t("credit_cards.tabs.overview.credit_toward_next"), response.body
+ assert_no_match I18n.t("credit_cards.tabs.overview.due_on", date: ""), response.body
+ end
+ end
+
+ test "credit card overview asks for a cycle when none is set" do
+ sign_in users(:family_admin)
+
+ get account_url(accounts(:credit_card), tab: "overview")
+
+ assert_response :success
+ assert_match I18n.t("credit_cards.tabs.overview.no_cycle_title"), response.body
+ end
+
test "account activity marks trade amounts as privacy-sensitive" do
trade_entry = entries(:trade)
expected_amount = ApplicationController.helpers.format_money(-trade_entry.amount_money)
diff --git a/test/controllers/concerns/self_hostable_test.rb b/test/controllers/concerns/self_hostable_test.rb
new file mode 100644
index 0000000000..6e4f054380
--- /dev/null
+++ b/test/controllers/concerns/self_hostable_test.rb
@@ -0,0 +1,46 @@
+require "test_helper"
+
+# SelfHostable's `verify_self_host_config` prepended before_action gates every
+# request on a reachable Redis when the app runs self-hosted. See
+# app/controllers/concerns/self_hostable.rb.
+class SelfHostableTest < ActionDispatch::IntegrationTest
+ setup do
+ sign_in @user = users(:empty)
+ end
+
+ test "lets the request through when self hosted and redis is reachable" do
+ with_self_hosting do
+ get privacy_path
+ assert_response :success
+ end
+ end
+
+ test "does not check redis when not self hosted" do
+ ApplicationController.any_instance.expects(:redis_connected?).never
+
+ get privacy_path
+ assert_response :success
+ end
+
+ test "redirects to the redis configuration error page when self hosted and redis is unreachable" do
+ with_self_hosting(redis_connected: false) do
+ get privacy_path
+ assert_redirected_to redis_configuration_error_path
+ end
+ end
+
+ test "redirects home from the error page once redis becomes reachable" do
+ with_self_hosting(redis_connected: true) do
+ get redis_configuration_error_path
+ assert_redirected_to root_path
+ assert_equal I18n.t("concerns.self_hostable.redis_configured"), flash[:notice]
+ end
+ end
+
+ test "renders the error page instead of redirecting to itself when redis is unreachable" do
+ with_self_hosting(redis_connected: false) do
+ get redis_configuration_error_path
+ assert_response :success
+ end
+ end
+end
diff --git a/test/controllers/credit_cards_controller_test.rb b/test/controllers/credit_cards_controller_test.rb
index febe7be89c..5d2793063b 100644
--- a/test/controllers/credit_cards_controller_test.rb
+++ b/test/controllers/credit_cards_controller_test.rb
@@ -93,6 +93,55 @@ class CreditCardsControllerTest < ActionDispatch::IntegrationTest
assert_enqueued_with(job: SyncJob)
end
+ test "updates the statement cycle" do
+ patch credit_card_path(@account), params: {
+ account: {
+ accountable_attributes: {
+ id: @account.accountable_id,
+ statement_close_day: 25,
+ due_day: 5
+ }
+ }
+ }
+
+ assert_redirected_to @account
+ assert_equal 25, @account.reload.credit_card.statement_close_day
+ assert_equal 5, @account.credit_card.due_day
+ end
+
+ test "clearing the statement cycle stores blanks as no cycle" do
+ @account.credit_card.update!(statement_close_day: 25, due_day: 5)
+
+ patch credit_card_path(@account), params: {
+ account: {
+ accountable_attributes: {
+ id: @account.accountable_id,
+ statement_close_day: "",
+ due_day: ""
+ }
+ }
+ }
+
+ assert_redirected_to @account
+ assert_nil @account.reload.credit_card.statement_close_day
+ assert_nil @account.credit_card.due_day
+ end
+
+ test "a statement cycle day outside the month is rejected" do
+ patch credit_card_path(@account), params: {
+ account: {
+ accountable_attributes: {
+ id: @account.accountable_id,
+ statement_close_day: 45,
+ due_day: 5
+ }
+ }
+ }
+
+ assert_response :unprocessable_entity
+ assert_nil @account.reload.credit_card.statement_close_day
+ end
+
test "updates enable banking balance interpretation flag when linked" do
enable_banking_account = create_linked_enable_banking_account
diff --git a/test/controllers/settings/providers_controller_test.rb b/test/controllers/settings/providers_controller_test.rb
index af30dd67b4..438b7daf54 100644
--- a/test/controllers/settings/providers_controller_test.rb
+++ b/test/controllers/settings/providers_controller_test.rb
@@ -615,15 +615,16 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTest
test "GET show warns on configured provider forms when self-hosted encryption keys are not explicitly configured" do
Setting["plaid_client_id"] = "test-client-id"
Setting["plaid_secret"] = "test-secret"
- Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)
ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(false)
- get settings_providers_url
+ with_self_hosting do
+ get settings_providers_url
- assert_response :success
- assert_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.title")
- assert_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.message")
- assert_includes response.body, I18n.t("settings.providers.drawer_trust_statement_encryption_unconfigured")
+ assert_response :success
+ assert_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.title")
+ assert_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.message")
+ assert_includes response.body, I18n.t("settings.providers.drawer_trust_statement_encryption_unconfigured")
+ end
ensure
Setting["plaid_client_id"] = nil
Setting["plaid_secret"] = nil
@@ -655,29 +656,31 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTest
end
test "GET connect_form warns when self-hosted encryption keys are not explicitly configured" do
- Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)
- ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(false)
+ with_self_hosting do
+ ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(false)
- get connect_form_settings_providers_path(provider_key: "ibkr")
+ get connect_form_settings_providers_path(provider_key: "ibkr")
- assert_response :success
- assert_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.title")
- assert_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.message")
- assert_includes response.body, I18n.t("settings.providers.drawer_trust_statement_encryption_unconfigured")
- refute_includes response.body, I18n.t("settings.providers.drawer_trust_statement")
+ assert_response :success
+ assert_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.title")
+ assert_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.message")
+ assert_includes response.body, I18n.t("settings.providers.drawer_trust_statement_encryption_unconfigured")
+ refute_includes response.body, I18n.t("settings.providers.drawer_trust_statement")
+ end
end
test "GET connect_form hides encryption warning when self-hosted encryption keys are configured" do
- Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)
- ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(true)
+ with_self_hosting do
+ ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(true)
- get connect_form_settings_providers_path(provider_key: "ibkr")
+ get connect_form_settings_providers_path(provider_key: "ibkr")
- assert_response :success
- refute_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.title")
- refute_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.message")
- assert_includes response.body, I18n.t("settings.providers.drawer_trust_statement")
- refute_includes response.body, I18n.t("settings.providers.drawer_trust_statement_encryption_unconfigured")
+ assert_response :success
+ refute_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.title")
+ refute_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.message")
+ assert_includes response.body, I18n.t("settings.providers.drawer_trust_statement")
+ refute_includes response.body, I18n.t("settings.providers.drawer_trust_statement_encryption_unconfigured")
+ end
end
test "GET connect_form hides encryption warning in managed mode" do
@@ -694,18 +697,19 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTest
end
test "GET connect_form uses shared encryption warning for provider panels" do
- Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)
- ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(false)
+ with_self_hosting do
+ ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(false)
- get connect_form_settings_providers_path(provider_key: "wise")
+ get connect_form_settings_providers_path(provider_key: "wise")
- assert_response :success
- assert_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.title")
- assert_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.message")
- refute_includes response.body, I18n.t("wise_items.provider_panel.encryption_warning.title")
- refute_includes response.body, I18n.t("wise_items.provider_panel.encryption_warning.message")
- assert_includes response.body, I18n.t("settings.providers.drawer_trust_statement_encryption_unconfigured")
- refute_includes response.body, I18n.t("settings.providers.drawer_trust_statement")
+ assert_response :success
+ assert_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.title")
+ assert_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.message")
+ refute_includes response.body, I18n.t("wise_items.provider_panel.encryption_warning.title")
+ refute_includes response.body, I18n.t("wise_items.provider_panel.encryption_warning.message")
+ assert_includes response.body, I18n.t("settings.providers.drawer_trust_statement_encryption_unconfigured")
+ refute_includes response.body, I18n.t("settings.providers.drawer_trust_statement")
+ end
end
test "GET show includes Trade Republic in bank sync providers" do
diff --git a/test/models/credit_card_test.rb b/test/models/credit_card_test.rb
index e1997293c6..0634680609 100644
--- a/test/models/credit_card_test.rb
+++ b/test/models/credit_card_test.rb
@@ -17,4 +17,369 @@ class CreditCardTest < ActiveSupport::TestCase
assert_nil CreditCard.debt_from_available_credit(credit_limit: nil, available_credit: BigDecimal("10"), clamp_overpayment: true)
assert_nil CreditCard.debt_from_available_credit(credit_limit: BigDecimal("0"), available_credit: BigDecimal("10"), clamp_overpayment: true)
end
+
+ test "statement cycle days are bounded to a real day of the month" do
+ card = CreditCard.new
+
+ card.statement_close_day = 0
+ assert_not card.valid?
+ assert card.errors[:statement_close_day].present?
+
+ card.statement_close_day = 32
+ assert_not card.valid?
+ assert card.errors[:statement_close_day].present?
+
+ card.statement_close_day = 31
+ card.due_day = 31
+ assert card.valid?
+ end
+
+ test "a card with no account has no statement cycle" do
+ assert_not CreditCard.new(statement_close_day: 25, due_day: 5).statement_cycle_configured?
+ end
+
+ test "a close day alone is not a cycle without an account" do
+ card = CreditCard.new(statement_close_day: 25)
+ card.account = accounts(:credit_card)
+
+ assert card.statement_cycle_configured?
+ end
+
+ test "a card with no close day has no cycle dates" do
+ card = CreditCard.new(due_day: 5)
+ card.account = accounts(:credit_card)
+
+ assert_not card.statement_cycle_configured?
+ assert_nil card.last_statement_close_date
+ assert_nil card.previous_statement_close_date
+ assert_nil card.next_statement_close_date
+ assert_nil card.next_payment_due_date
+ assert_nil card.days_until_due
+ assert_nil card.last_statement_balance_money
+ assert_nil card.accrued_since_last_close_money
+ end
+
+ test "a close day without a due day still closes but never falls due" do
+ card = CreditCard.new(statement_close_day: 25)
+ card.account = accounts(:credit_card)
+
+ assert_equal Date.new(2026, 10, 25), card.next_statement_close_date(as_of: Date.new(2026, 10, 16))
+ assert_nil card.next_payment_due_date(as_of: Date.new(2026, 10, 16))
+ assert_nil card.days_until_due(as_of: Date.new(2026, 10, 16))
+ end
+
+ test "the last close is the close already past, and today counts as closed" do
+ card = statement_card(close_day: 25, due_day: 5)
+
+ assert_equal Date.new(2026, 9, 25), card.last_statement_close_date(as_of: Date.new(2026, 10, 16))
+ assert_equal Date.new(2026, 10, 25), card.last_statement_close_date(as_of: Date.new(2026, 10, 25))
+ assert_equal Date.new(2026, 9, 25), card.last_statement_close_date(as_of: Date.new(2026, 10, 24))
+ end
+
+ test "the previous close is one cycle back and the next one is one cycle on" do
+ card = statement_card(close_day: 25, due_day: 5)
+
+ assert_equal Date.new(2026, 8, 25), card.previous_statement_close_date(as_of: Date.new(2026, 10, 16))
+ assert_equal Date.new(2026, 10, 25), card.next_statement_close_date(as_of: Date.new(2026, 10, 16))
+ assert_equal Date.new(2026, 11, 25), card.next_statement_close_date(as_of: Date.new(2026, 10, 25))
+ end
+
+ test "a close day past the month end clamps to the last day of that month" do
+ card = statement_card(close_day: 31, due_day: 20)
+
+ assert_equal Date.new(2026, 10, 31), card.last_statement_close_date(as_of: Date.new(2026, 11, 3))
+ assert_equal Date.new(2026, 11, 30), card.next_statement_close_date(as_of: Date.new(2026, 11, 3))
+ assert_equal Date.new(2028, 2, 29), card.last_statement_close_date(as_of: Date.new(2028, 3, 1))
+ assert_equal Date.new(2027, 2, 28), card.last_statement_close_date(as_of: Date.new(2027, 3, 1))
+ end
+
+ test "a due day after the close day falls in the following month" do
+ card = statement_card(close_day: 25, due_day: 5)
+
+ assert_equal Date.new(2026, 11, 5), card.next_payment_due_date(as_of: Date.new(2026, 10, 16))
+ assert_equal 20, card.days_until_due(as_of: Date.new(2026, 10, 16))
+ end
+
+ # The close and the due day both landing in the same calendar month is the
+ # case a "next close" anchor gets wrong: the statement that closed on the
+ # 16th of this month is due on the 26th of this month.
+ test "a card closing early in the month is due later in the same month" do
+ card = statement_card(close_day: 10, due_day: 26)
+
+ assert_equal Date.new(2026, 10, 10), card.last_statement_close_date(as_of: Date.new(2026, 10, 16))
+ assert_equal Date.new(2026, 10, 26), card.next_payment_due_date(as_of: Date.new(2026, 10, 16))
+ assert_equal 10, card.days_until_due(as_of: Date.new(2026, 10, 16))
+ end
+
+ test "a card is still due today on the due date itself" do
+ card = statement_card(close_day: 10, due_day: 26)
+
+ assert_equal Date.new(2026, 10, 26), card.next_payment_due_date(as_of: Date.new(2026, 10, 26))
+ assert_equal 0, card.days_until_due(as_of: Date.new(2026, 10, 26))
+ end
+
+ test "a passed due date gives way to the following statement" do
+ card = statement_card(close_day: 10, due_day: 26)
+
+ assert_equal Date.new(2026, 11, 26), card.next_payment_due_date(as_of: Date.new(2026, 10, 27))
+ assert_equal 30, card.days_until_due(as_of: Date.new(2026, 10, 27))
+ end
+
+ test "the amount the next payment is made on is the statement already closed" do
+ card = statement_card(close_day: 10, due_day: 26)
+ account = card.account
+ as_of = Date.new(2026, 10, 16)
+
+ charge(account, Date.new(2026, 9, 20), 300)
+ charge(account, Date.new(2026, 10, 12), 40)
+ charge(account, Date.new(2026, 10, 14), 60)
+
+ # The 300 statement is due on the 26th of this month, which is the payment
+ # the cardholder is being asked about. The 40 and 60 land on the statement
+ # that closes on the 10th of November and are still building.
+ assert_equal 300, card.last_statement_balance_money(as_of: as_of).amount
+ assert_equal 100, card.accrued_since_last_close_money(as_of: as_of).amount
+ end
+
+ test "a due day later in the same month is due this month" do
+ card = statement_card(close_day: 5, due_day: 25)
+
+ assert_equal Date.new(2026, 10, 25), card.next_payment_due_date(as_of: Date.new(2026, 10, 16))
+ assert_equal 9, card.days_until_due(as_of: Date.new(2026, 10, 16))
+ end
+
+ test "a due day landing on the close day is left alone" do
+ card = statement_card(close_day: 15, due_day: 15)
+
+ # Same day is a real arrangement, so the payment is not pushed a month out
+ # for being equal to the close; it simply falls due the day it closes.
+ assert_equal Date.new(2026, 10, 15), card.payment_due_date_for(Date.new(2026, 10, 15))
+ # Read the day after, that one has passed and the next statement is due.
+ assert_equal Date.new(2026, 11, 15), card.next_payment_due_date(as_of: Date.new(2026, 10, 16))
+ end
+
+ test "a due day earlier than the close day wraps even when clamping collapses both onto one day" do
+ card = statement_card(close_day: 31, due_day: 28)
+
+ # February collapses the 31st and the 28th onto the same day. The cardholder
+ # configured the due day BEFORE the close day, so the statement that closed
+ # on 28 February is due on 28 March -- not due the day it closes, and not
+ # skipped over for 28 April once March arrives.
+ travel_to Date.new(2026, 3, 1) do
+ assert_equal Date.new(2026, 2, 28), card.last_statement_close_date
+ assert_equal Date.new(2026, 3, 28), card.payment_due_date_for(Date.new(2026, 2, 28))
+ assert_equal Date.new(2026, 3, 28), card.next_payment_due_date
+ end
+ end
+
+ test "an unpaid passed due date stays overdue rather than giving way" do
+ card = statement_card(close_day: 10, due_day: 26)
+ charge(card.account, Date.new(2026, 9, 20), 300)
+
+ # The statement that closed on 10 October came to $300 and nothing has paid
+ # it: the 26th passing does not make the debt go away.
+ travel_to Date.new(2026, 10, 27) do
+ assert_equal Date.new(2026, 10, 26), card.next_payment_due_date
+ assert_equal(-1, card.days_until_due)
+ end
+ end
+
+ test "a settled statement gives way to the following one once its due date passes" do
+ card = statement_card(close_day: 10, due_day: 26)
+ charge(card.account, Date.new(2026, 9, 20), 300)
+ # Paid after the statement closed but before it fell due.
+ charge(card.account, Date.new(2026, 10, 20), -300)
+
+ travel_to Date.new(2026, 10, 27) do
+ assert_equal Date.new(2026, 11, 26), card.next_payment_due_date
+ assert_equal 30, card.days_until_due
+ end
+ end
+
+ test "a partly paid statement keeps its due date until it is paid in full" do
+ card = statement_card(close_day: 10, due_day: 26)
+ charge(card.account, Date.new(2026, 9, 20), 300)
+ charge(card.account, Date.new(2026, 10, 20), -100)
+
+ travel_to Date.new(2026, 10, 27) do
+ assert_equal Date.new(2026, 10, 26), card.next_payment_due_date
+ assert_equal(-1, card.days_until_due)
+ end
+ end
+
+ test "the last statement balance is everything owed through the close" do
+ card = statement_card(close_day: 25, due_day: 5)
+ account = card.account
+ as_of = Date.new(2026, 10, 16)
+
+ # The statement that closed on 25 September bills the debt carried in plus
+ # this cycle's activity: $1,999 from before the window, $100 charged in it,
+ # less the $40 paid in it -- not merely the $60 the window sums to.
+ charge_in_window = charge(account, Date.new(2026, 9, 10), 100)
+ charge_before_window = charge(account, Date.new(2026, 8, 20), 999)
+ charge_on_previous_close = charge(account, Date.new(2026, 8, 25), 1_000)
+ payment_in_window = charge(account, Date.new(2026, 9, 20), -40)
+
+ # Charges after the close belong to the statement still building, not this one.
+ charge_after_close = charge(account, Date.new(2026, 9, 26), 500)
+
+ assert_equal 2_059, card.last_statement_balance_money(as_of: as_of).amount
+ assert_equal "USD", card.last_statement_balance_money(as_of: as_of).currency.iso_code
+
+ assert charge_in_window.persisted?
+ assert charge_before_window.persisted?
+ assert charge_on_previous_close.persisted?
+ assert payment_in_window.persisted?
+ assert charge_after_close.persisted?
+ end
+
+ test "the balance since the last close counts only what has been charged since" do
+ card = statement_card(close_day: 25, due_day: 5)
+ account = card.account
+ as_of = Date.new(2026, 10, 16)
+
+ charge(account, Date.new(2026, 9, 10), 100)
+ charge(account, Date.new(2026, 9, 26), 500)
+ charge(account, Date.new(2026, 10, 3), 20)
+
+ assert_equal 520, card.accrued_since_last_close_money(as_of: as_of).amount
+ assert_equal 100, card.last_statement_balance_money(as_of: as_of).amount
+ end
+
+ test "a charge on the close day lands on the statement that closes that day" do
+ card = statement_card(close_day: 25, due_day: 5)
+ account = card.account
+ as_of = Date.new(2026, 10, 16)
+
+ charge(account, Date.new(2026, 9, 25), 70)
+
+ assert_equal 70, 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 card with no entries in the window has a zero statement, not an unknown one" do
+ card = statement_card(close_day: 25, due_day: 5)
+
+ assert_equal 0, card.last_statement_balance_money(as_of: Date.new(2026, 10, 16)).amount
+ assert_equal 0, card.accrued_since_last_close_money(as_of: Date.new(2026, 10, 16)).amount
+ end
+
+ test "pending entries and split parents stay out of the statement, as they do of the balance" do
+ card = statement_card(close_day: 25, due_day: 5)
+ account = card.account
+ as_of = Date.new(2026, 10, 16)
+
+ charge(account, Date.new(2026, 9, 10), 100)
+
+ pending = charge(account, Date.new(2026, 9, 11), 500)
+ Transaction.find(pending.entryable_id).update!(extra: { "plaid" => { "pending" => true } })
+
+ # A split parent is replaced by its children, so the 300 stays in the
+ # statement once and the parent row itself never counts.
+ parent = charge(account, Date.new(2026, 9, 12), 300)
+ [ 200, 100 ].each do |portion|
+ account.entries.create!(
+ name: "Split portion",
+ date: Date.new(2026, 9, 12),
+ amount: portion,
+ currency: "USD",
+ parent_entry: parent,
+ entryable: Transaction.new
+ )
+ end
+
+ assert_equal 400, card.last_statement_balance_money(as_of: as_of).amount
+ end
+
+ test "a card with entries in another currency reports no statement rather than a wrong one" do
+ card = statement_card(close_day: 25, due_day: 5)
+ account = card.account
+
+ charge(account, Date.new(2026, 9, 10), 100)
+ foreign = account.entries.create!(
+ name: "Foreign charge",
+ date: Date.new(2026, 9, 11),
+ amount: 500,
+ currency: "EUR",
+ entryable: Transaction.new
+ )
+
+ assert_nil card.last_statement_balance_money(as_of: Date.new(2026, 10, 16))
+ assert_equal 0, card.accrued_since_last_close_money(as_of: Date.new(2026, 10, 16)).amount
+
+ foreign.destroy!
+ assert_equal 100, card.last_statement_balance_money(as_of: Date.new(2026, 10, 16)).amount
+ end
+
+ test "an entry with no currency reports no statement rather than a partial one" do
+ card = statement_card(close_day: 25, due_day: 5)
+ account = card.account
+
+ charge(account, Date.new(2026, 9, 10), 100)
+ before_close = charge(account, Date.new(2026, 9, 11), 500)
+ after_close = charge(account, Date.new(2026, 9, 26), 250)
+ before_close.update_column(:currency, nil)
+ after_close.update_column(:currency, nil)
+
+ # An entry with no currency is one we cannot add up. where.not(currency:)
+ # would not match it, so without the refusal it would drop out of the sum
+ # and the Overview would quote a partial total as the whole statement.
+ assert_nil card.last_statement_balance_money(as_of: Date.new(2026, 10, 16))
+ assert_nil card.accrued_since_last_close_money(as_of: Date.new(2026, 10, 16))
+ end
+
+ test "the minimum payment shortfall reads against the last statement" do
+ travel_to Date.new(2026, 10, 16) do
+ card = statement_card(close_day: 25, due_day: 5, minimum_payment: 100)
+
+ charge(card.account, Date.new(2026, 9, 10), 250)
+ assert card.minimum_payment_shortfall?
+
+ card.update!(minimum_payment: 500)
+ assert_not card.minimum_payment_shortfall?
+ end
+ end
+
+ test "a card with no minimum payment recorded is not in shortfall" do
+ card = statement_card(close_day: 25, due_day: 5, minimum_payment: nil)
+
+ charge(card.account, Date.new(2026, 9, 10), 250)
+
+ assert_not card.minimum_payment_shortfall?
+ end
+
+ private
+ def statement_card(close_day:, due_day:, minimum_payment: 100)
+ card = CreditCard.create!(
+ statement_close_day: close_day,
+ due_day: due_day,
+ minimum_payment: minimum_payment,
+ apr: 18.99,
+ available_credit: 5_000
+ )
+
+ account = Account.create!(
+ family: accounts(:credit_card).family,
+ name: "Statement Cycle Card",
+ balance: 0,
+ currency: "USD",
+ classification: "liability",
+ status: "active",
+ accountable: card
+ )
+
+ card.reload
+ 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!(
+ name: "Statement test entry",
+ date: date,
+ amount: amount,
+ currency: account.currency,
+ entryable: Transaction.new
+ )
+ end
end
diff --git a/test/models/plaid_account/liabilities/credit_processor_test.rb b/test/models/plaid_account/liabilities/credit_processor_test.rb
index 04b1000512..f237bf491f 100644
--- a/test/models/plaid_account/liabilities/credit_processor_test.rb
+++ b/test/models/plaid_account/liabilities/credit_processor_test.rb
@@ -35,5 +35,64 @@ class PlaidAccount::Liabilities::CreditProcessorTest < ActiveSupport::TestCase
assert_nil @plaid_account.current_account.credit_card.minimum_payment
assert_nil @plaid_account.current_account.credit_card.apr
+ assert_nil @plaid_account.current_account.credit_card.statement_close_day
+ assert_nil @plaid_account.current_account.credit_card.due_day
end
+
+ test "records the statement cycle from the last issue date and next due date" do
+ process_credit(
+ minimum_payment_amount: 100,
+ aprs: [ { apr_percentage: 15.0 } ],
+ last_statement_issue_date: "2025-05-19",
+ next_payment_due_date: "2025-06-19"
+ )
+
+ card = @plaid_account.current_account.credit_card
+ assert_equal 19, card.statement_close_day
+ assert_equal 19, card.due_day
+ end
+
+ test "a cycle already set by hand survives a sync" do
+ process_credit(
+ last_statement_issue_date: "2025-05-19",
+ next_payment_due_date: "2025-06-19"
+ )
+ @plaid_account.current_account.credit_card.update!(statement_close_day: 3, due_day: 21)
+
+ process_credit(
+ last_statement_issue_date: "2025-07-02",
+ next_payment_due_date: "2025-07-23"
+ )
+
+ card = @plaid_account.current_account.credit_card
+ assert_equal 3, card.statement_close_day
+ assert_equal 21, card.due_day
+ end
+
+ test "one half of the cycle can be filled in without the other" do
+ process_credit(last_statement_issue_date: "2025-05-19")
+
+ card = @plaid_account.current_account.credit_card
+ assert_equal 19, card.statement_close_day
+ assert_nil card.due_day
+ end
+
+ test "an unparseable statement date does not fail the sync" do
+ process_credit(
+ minimum_payment_amount: 100,
+ aprs: [ { apr_percentage: 15.0 } ],
+ last_statement_issue_date: "not-a-date"
+ )
+
+ card = @plaid_account.current_account.credit_card
+ assert_nil card.statement_close_day
+ assert_equal 100, card.minimum_payment
+ assert_equal 15.0, card.apr
+ end
+
+ private
+ def process_credit(payload)
+ @plaid_account.update!(raw_liabilities_payload: { credit: payload })
+ PlaidAccount::Liabilities::CreditProcessor.new(@plaid_account).process
+ end
end
diff --git a/test/models/security/price/importer_test.rb b/test/models/security/price/importer_test.rb
index 547c4eb88e..705f289cf4 100644
--- a/test/models/security/price/importer_test.rb
+++ b/test/models/security/price/importer_test.rb
@@ -496,38 +496,44 @@ class Security::Price::ImporterTest < ActiveSupport::TestCase
test "retries fetch when refetchable provisional prices exist" do
Security::Price.delete_all
- # Skip if today is a weekend
- return if Date.current.saturday? || Date.current.sunday?
+ # A provisional price for "today" is only refetchable on a weekday, where the
+ # provider would have a real quote for it. Pin to the next weekday rather
+ # than bailing out at the top of the test, so the case is covered every day
+ # it is run instead of silently vanishing on weekends.
+ test_date = Date.current
+ test_date += 1.day while test_date.saturday? || test_date.sunday?
- # Pre-populate with provisional price for today
- Security::Price.create!(
- security: @security,
- date: Date.current,
- price: 100,
- currency: "USD",
- provisional: true
- )
+ travel_to test_date do
+ # Pre-populate with provisional price for today
+ Security::Price.create!(
+ security: @security,
+ date: Date.current,
+ price: 100,
+ currency: "USD",
+ provisional: true
+ )
- # Provider now returns today's actual price
- provider_response = provider_success_response([
- OpenStruct.new(security: @security, date: Date.current, price: 165, currency: "USD")
- ])
+ # Provider now returns today's actual price
+ provider_response = provider_success_response([
+ OpenStruct.new(security: @security, date: Date.current, price: 165, currency: "USD")
+ ])
- @provider.expects(:fetch_security_prices)
- .with(symbol: @security.ticker, exchange_operating_mic: @security.exchange_operating_mic,
- start_date: get_provider_fetch_start_date(Date.current), end_date: Date.current)
- .returns(provider_response)
+ @provider.expects(:fetch_security_prices)
+ .with(symbol: @security.ticker, exchange_operating_mic: @security.exchange_operating_mic,
+ start_date: get_provider_fetch_start_date(Date.current), end_date: Date.current)
+ .returns(provider_response)
- Security::Price::Importer.new(
- security: @security,
- security_provider: @provider,
- start_date: Date.current,
- end_date: Date.current
- ).import_provider_prices
+ Security::Price::Importer.new(
+ security: @security,
+ security_provider: @provider,
+ start_date: Date.current,
+ end_date: Date.current
+ ).import_provider_prices
- db_price = Security::Price.find_by(security: @security, date: Date.current)
- assert_equal 165, db_price.price, "Price should be updated from provider"
- assert_not db_price.provisional, "Price should no longer be provisional after provider returns real price"
+ db_price = Security::Price.find_by(security: @security, date: Date.current)
+ assert_equal 165, db_price.price, "Price should be updated from provider"
+ assert_not db_price.provisional, "Price should no longer be provisional after provider returns real price"
+ end
end
test "skips fetch when all prices are non-provisional" do
diff --git a/test/test_helper.rb b/test/test_helper.rb
index 0e592be2c7..88007a11bd 100644
--- a/test/test_helper.rb
+++ b/test/test_helper.rb
@@ -106,8 +106,19 @@ module ActiveSupport
ClimateControl.modify(**overrides, &block)
end
- def with_self_hosting
+ # Self-hosted mode makes ApplicationController run SelfHostable's
+ # `verify_self_host_config` prepended before_action, which pings Redis and
+ # redirects to the Redis configuration error page when it can't connect.
+ # That check is an infrastructure concern, not what the ~100 callers of this
+ # helper are testing, and it depends on REDIS_URL being set and the service
+ # being reachable (Redis.new falls back to localhost:6379 otherwise, which
+ # is not where Redis runs in the devcontainer or docker compose). Stub the
+ # ping so self-hosting tests exercise the controller under test instead of
+ # the developer's Redis setup. Tests that care about a Redis outage stub
+ # `redis_connected?` to false themselves.
+ def with_self_hosting(redis_connected: true)
Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)
+ ApplicationController.any_instance.stubs(:redis_connected?).returns(redis_connected)
yield
end