The personal finance app for everyone (by everyone)
Ruby
Allow scheduling future-dated transactions and transfers (#3262)
JulienGourmetb7ae0e31811c
diff --git a/app/components/UI/account/activity_date.html.erb b/app/components/UI/account/activity_date.html.erbindex 1b2e25a537..c4a8a60472 100644--- a/app/components/UI/account/activity_date.html.erb+++ b/app/components/UI/account/activity_date.html.erb@@ -20,8 +20,11 @@<div class="flex items-center gap-4"><div class="flex items-center gap-2">+ <% if projected? %>+ <%= render DS::Pill.new(label: t("UI.account.activity_date.projected"), tone: :neutral, marker: false, icon: "calendar") %>+ <% end %><span class="font-medium privacy-sensitive"><%= end_balance_money.format %></span>- <%= render DS::Tooltip.new(text: t("UI.account.activity_date.balance_tooltip"), placement: "left", size: "sm", as: :span) %>+ <%= render DS::Tooltip.new(text: t(projected? ? "UI.account.activity_date.projected_balance_tooltip" : "UI.account.activity_date.balance_tooltip"), placement: "left", size: "sm", as: :span) %></div><%= helpers.icon "chevron-down", class: "group-open:rotate-180" %></div>diff --git a/app/components/UI/account/activity_date.rb b/app/components/UI/account/activity_date.rbindex 667435a696..b0b6022e94 100644--- a/app/components/UI/account/activity_date.rb+++ b/app/components/UI/account/activity_date.rb@@ -1,7 +1,7 @@class UI::Account::ActivityDate < ApplicationComponentattr_reader :account, :data- delegate :date, :entries, :balance, :transfers, :split_parents, to: :data+ delegate :date, :entries, :balance, :projected_balance_money, :transfers, :split_parents, to: :datadef initialize(account:, data:)@account = account@@ -16,8 +16,21 @@ class UI::Account::ActivityDate < ApplicationComponentaccountend+ # Scheduled (future-dated) entries have no Balance row yet -- see+ # Entry#scheduled?. `projected_balance_money` estimates one from the+ # account's current balance plus scheduled entries through this date.+ # Any other date without a Balance row (e.g. a pre-anchor gap) keeps the+ # historical zero rather than showing today's balance as that date's+ # end-of-day balance.def end_balance_money- balance&.end_balance_money || Money.new(0, account.currency)+ return balance.end_balance_money if balance+ return projected_balance_money if projected_balance_money++ Money.new(0, account.currency)+ end++ def projected?+ balance.nil? && projected_balance_money.present?enddef broadcast_refresh!diff --git a/app/components/UI/account/chart.html.erb b/app/components/UI/account/chart.html.erbindex a4db421551..8c78ddb780 100644--- a/app/components/UI/account/chart.html.erb+++ b/app/components/UI/account/chart.html.erb@@ -5,7 +5,15 @@<%= tag.p title, class: "text-sm font-medium text-secondary" %><% if account.supports_trades? %>- <%= render "investments/value_tooltip", balance: account.balance_money, holdings: holdings_value_money, cash: account.cash_balance_money %>+ <% has_scheduled = account.scheduled_entries_total_money.amount.abs.round.nonzero? %>+ <%= render "investments/value_tooltip",+ balance: account.balance_money,+ holdings: holdings_value_money,+ cash: account.cash_balance_money,+ scheduled: (account.scheduled_entries_total_money if has_scheduled),+ projected: (account.projected_balance_money if has_scheduled) %>+ <% elsif account.scheduled_entries_total_money.amount.abs.round.nonzero? %>+ <%= render "accounts/scheduled_balance_tooltip", account: account %><% end %></div><div class="flex flex-row gap-2 items-baseline">diff --git a/app/controllers/concerns/localize.rb b/app/controllers/concerns/localize.rbindex 54a43e624e..d482b31fb4 100644--- a/app/controllers/concerns/localize.rb+++ b/app/controllers/concerns/localize.rb@@ -115,46 +115,14 @@ module LocalizeTime.use_zone(resolved_timezone, &action)end- # How often to write a DebugLogEntry for the same (family, bad value) pair.- # switch_timezone runs on every request, so without this an affected- # family would write one row per page view forever.- INVALID_TIMEZONE_LOG_INTERVAL = 1.day-- # Family#timezone is a free-text IANA name (e.g. from an older DB dump, or- # a zone the tzdata maintainers later renamed, like the historical- # "Europe/Kiev" -> "Europe/Kyiv" switch). `Time.use_zone` raises- # ArgumentError on anything it doesn't recognize, which would otherwise- # take down every request/render for the affected family -- including the- # login page, since this runs on every request. Validate first and fall- # back to the app default instead of crashing.+ # `Time.use_zone` raises ArgumentError on anything it doesn't recognize,+ # which would otherwise take down every request/render for the affected+ # family -- including the login page, since this runs on every request.+ # Family#resolved_time_zone validates and falls back to the app default+ # instead of crashing; it's also what Sync#perform uses in the background,+ # so a scheduled entry's arrival date agrees with the family's clock in+ # both places.def resolved_timezone- family = Current.family- requested = family.try(:timezone)- return Time.zone if requested.blank?-- zone = ActiveSupport::TimeZone[requested]- return zone if zone.present?-- log_invalid_timezone_once(family, requested)- Time.zone- end-- def log_invalid_timezone_once(family, requested)- cache_key = [ "invalid_family_timezone", family.id, requested ]-- # `fetch` is read-then-write, not atomic -- two concurrent requests could- # both see a miss and both log. `write(unless_exist: true)` maps to- # Redis's atomic SET NX in production, so only one request ever wins the- # lease and logs.- lease_acquired = Rails.cache.write(cache_key, true, expires_in: INVALID_TIMEZONE_LOG_INTERVAL, unless_exist: true)- return unless lease_acquired-- DebugLogEntry.capture(- category: "other",- level: "warn",- message: "Invalid family timezone #{requested.inspect}, falling back to #{Time.zone.name}",- source: "Localize#switch_timezone",- family: family- )+ Current.family&.resolved_time_zone || Time.zoneendenddiff --git a/app/jobs/entry_scheduled_sync_job.rb b/app/jobs/entry_scheduled_sync_job.rbnew file mode 100644index 0000000000..85fba64018--- /dev/null+++ b/app/jobs/entry_scheduled_sync_job.rb@@ -0,0 +1,36 @@+class EntryScheduledSyncJob < ApplicationJob+ # Scheduled (future-dated) entries are excluded from balance calculations+ # until their date arrives (see Entry#scheduled?, Balance::SyncCache). That+ # normally happens on the next sync -- but if host-wide auto-sync+ # (Setting.auto_sync_enabled) and the family's auto_sync_on_login are both+ # disabled, nothing would otherwise trigger a sync on that date. This job+ # is the fallback: it fires once, on the entry's date, and simply asks the+ # account to sync -- a cheap no-op if a sync already happened by then.+ def perform(entry_id)+ entry = Entry.find_by(id: entry_id)+ return unless entry++ entry.account.sync_later+ end++ def self.schedule_for(entry)+ return unless entry.scheduled?++ # A few minutes past midnight on the entry's date, so Date.current has+ # definitively rolled over (avoids clock-skew edge cases) by run time.+ # Midnight in the family's zone, as Sync#perform judges the date there --+ # imports and bulk updates call this from jobs running in the app's zone.+ run_at = entry.date.in_time_zone(entry.account.family.resolved_time_zone) + 5.minutes+ set(wait_until: run_at).perform_later(entry.id)+ end++ # Batch variant for paths that write many entries without going through+ # Entry#sync_account_later (imports, bulk updates). Enqueues one job per+ # (account, date) -- they'd all sync the same account on the same day.+ def self.schedule_for_entries(entries)+ entries.where("entries.date > ?", Date.current)+ .select("DISTINCT ON (entries.account_id, entries.date) entries.*")+ .order("entries.account_id, entries.date")+ .each { |entry| schedule_for(entry) }+ end+enddiff --git a/app/models/account.rb b/app/models/account.rbindex 6029927a3d..83623bd3df 100644--- a/app/models/account.rb+++ b/app/models/account.rb@@ -39,6 +39,43 @@ class Account < ApplicationRecordmonetize :balance, :cash_balance+ # Sum of scheduled (future-dated) entries, signed and converted the same way+ # Balance::BaseCalculator#signed_entry_flows treats real flows -- so the+ # projection stays consistent with what the balance will actually become+ # once these entries land. Non-cash valuation-only accounts (Property,+ # Vehicle, etc.) ignore transactions entirely for balance purposes, same as+ # Balance::BaseCalculator#flows_for_date -- see Entry#scheduled?.+ #+ # Trades are included only when qty is 0 (Dividend/Interest): those are pure+ # cash flows with no offsetting holdings change, same shape as a Transaction.+ # A Buy/Sell/Transfer/etc. moves value between cash and holdings rather than+ # into or out of the account, so summing its raw amount here would+ # double-count against Balance::BaseCalculator#market_value_change_on_date+ # once the trade lands.+ # `through_date` bounds the scheduled window to entries dated on or before+ # it (inclusive) -- used to project the balance as of a specific future+ # date (see Account::ActivityFeedData) instead of the account's fully+ # projected total.+ #+ # The flows are loaded and converted once per instance (see+ # #scheduled_entry_flows), so the chart tooltip and every projected date+ # group in the activity feed share one query and one FX pass.+ def scheduled_entries_total_money(through_date: nil)+ flows = scheduled_entry_flows+ flows = flows.select { |date, _| date <= through_date } if through_date++ Money.new(flows.sum { |_, amount| amount }, currency)+ end++ def reload(*)+ @scheduled_entry_flows = nil+ super+ end++ def projected_balance_money+ balance_money + scheduled_entries_total_money+ end+enum :classification, { asset: "asset", liability: "liability" }, validate: { allow_nil: true }VISIBLE_STATUSES = %w[draft active].freeze@@ -924,6 +961,41 @@ class Account < ApplicationRecordendprivate+ # [date, signed amount in account currency] for each scheduled entry that+ # contributes to the projection.+ def scheduled_entry_flows+ @scheduled_entry_flows ||= if balance_type == :non_cash && accountable_type != "Loan"+ []+ else+ entries.excluding_pending.excluding_split_parents+ .where(entryable_type: [ "Transaction", "Trade" ])+ .where("entries.date > ?", Date.current)+ .includes(:entryable)+ .filter_map { |entry| (amount = convert_scheduled_entry_amount(entry)) && [ entry.date, amount ] }+ end+ end++ # Converts a scheduled entry's amount into this account's currency, signed+ # the same way flows_for_date treats it (see Balance::BaseCalculator).+ # Returns nil when the entry should not contribute -- a Buy/Sell trade+ # (moves value between cash and holdings, not into/out of the account) or+ # an unconvertible currency pair. Dropping the latter instead of using the+ # raw, unconverted amount matches Balance::SyncCache#converted_entries,+ # which drops the same entry outright once it materializes (see #1143) --+ # a projection that doesn't drop it would disagree with the balance it's+ # supposed to preview.+ def convert_scheduled_entry_amount(entry)+ return nil if entry.entryable_type == "Trade" && entry.entryable.qty.nonzero?++ custom_rate = entry.entryable.exchange_rate if entry.entryable.respond_to?(:exchange_rate)+ converted = begin+ entry.amount_money.exchange_to(currency, date: entry.date, custom_rate: custom_rate).amount+ rescue Money::ConversionError+ return nil+ end++ asset? ? -converted : converted+ end# perform_later raises (the Sidekiq adapter re-raises RedisClient errors) or# returns false (ActiveJob::EnqueueError). Either way the status goes back.diff --git a/app/models/account/activity_feed_data.rb b/app/models/account/activity_feed_data.rbindex 78099065d9..ebd61b96ae 100644--- a/app/models/account/activity_feed_data.rb+++ b/app/models/account/activity_feed_data.rb@@ -2,7 +2,7 @@# This data object is useful for avoiding N+1 queries and having an easy way to pass around the required data to the# activity feed component in controllers and background jobs that refresh it.class Account::ActivityFeedData- ActivityDateData = Data.define(:date, :entries, :balance, :transfers, :split_parents)+ ActivityDateData = Data.define(:date, :entries, :balance, :projected_balance_money, :transfers, :split_parents)attr_reader :account, :entries, :split_parents@@ -15,10 +15,16 @@ class Account::ActivityFeedDatadef entries_by_date@entries_by_date_objects ||= begingrouped_entries.map do |date, date_entries|+ balance = balance_for_date(date)+ActivityDateData.new(date: date,entries: date_entries,- balance: balance_for_date(date),+ balance: balance,+ # Scheduled (future-dated) entries have no Balance row yet -- see+ # Entry#scheduled?. Project one instead of leaving the date group+ # with nothing to show.+ projected_balance_money: balance ? nil : projected_balance_money_for(date),transfers: transfers_for_date(date),split_parents: split_parents)@@ -31,6 +37,12 @@ class Account::ActivityFeedDatabalances_by_date[date]end+ def projected_balance_money_for(date)+ return nil unless date > Date.current++ account.balance_money + account.scheduled_entries_total_money(through_date: date)+ end+def transfers_for_date(date)transfers_by_date[date] || []enddiff --git a/app/models/account/provider_import_adapter.rb b/app/models/account/provider_import_adapter.rbindex 30647aa706..29e3d4a20b 100644--- a/app/models/account/provider_import_adapter.rb+++ b/app/models/account/provider_import_adapter.rb@@ -1,4 +1,6 @@class Account::ProviderImportAdapter+ SCHEDULED_MATCH_WINDOW_DAYS = 7+attr_reader :account, :skipped_entries# @param account [Account] the account every import through this adapter lands on@@ -110,8 +112,19 @@ class Account::ProviderImportAdapter# before linking their account to a provider# Note: We don't pass name here to allow matching even when provider formats names differentlyif entry.new_record? && allow_heuristic_matching- duplicate = find_duplicate_transaction(date: date, amount: amount, currency: currency)- if duplicate+ scheduled = find_scheduled_transaction(date: date, amount: amount, currency: currency)+ duplicate = find_duplicate_transaction(date: date, amount: amount, currency: currency) unless scheduled++ if scheduled+ # A bill or paycheck the user entered ahead of time has now been+ # booked. Claim it even when the user's edits protect it: the+ # enrichment below still respects their locks (name, category, notes),+ # but the provider's date and pending state must apply -- otherwise+ # the entry stays on its expected day, and a pending claim would never+ # be recognized when the booked version arrives under a new id.+ entry = scheduled+ entry.assign_attributes(external_id: external_id, source: source, date: date)+ elsif duplicate# Check if duplicate is protected - if so, link but don't modifyif duplicate.protected_from_sync?duplicate.update!(external_id: external_id, source: source)@@ -827,6 +840,25 @@ class Account::ProviderImportAdaptercandidates.to_a.min_by { |entry| [ (entry.date - date).abs, entry.created_at ] }end+ # Finds a manual transaction the user entered ahead of its date -- an+ # upcoming bill or paycheck (see Entry#scheduled?) -- that the provider has+ # now booked. Providers rarely book on exactly the expected day, so this+ # allows a few days either side of it, but still requires the exact amount+ # and currency. Only entries created before their own date qualify, so+ # ordinary manual entries keep find_duplicate_transaction's exact-date rule.+ #+ # @return [Entry, nil] the closest-dated match, or nil+ def find_scheduled_transaction(date:, amount:, currency:, date_window: SCHEDULED_MATCH_WINDOW_DAYS)+ date = Date.parse(date.to_s) unless date.is_a?(Date)++ account.entries+ .where(entryable_type: "Transaction", external_id: nil, amount: amount, currency: currency)+ .where(date: (date - date_window.days)..(date + date_window.days))+ .where("entries.created_at < entries.date")+ .to_a+ .min_by { |entry| [ (entry.date - date).abs, entry.created_at ] }+ end+# Finds a pending transaction that likely matches a newly posted transaction# Used to reconcile pending→posted when SimpleFIN gives different IDs for the same transaction#diff --git a/app/models/balance/base_calculator.rb b/app/models/balance/base_calculator.rbindex 404d7b43f1..76002b3cfe 100644--- a/app/models/balance/base_calculator.rb+++ b/app/models/balance/base_calculator.rb@@ -31,8 +31,15 @@ class Balance::BaseCalculator# branches) and the underlying MIN(date) is a non-trivial scan on accounts# with large entry histories. Calculator instances are per-sync, so there is# no staleness concern.+ # Clamped at Date.current: when an account's only entries are scheduled+ # (future-dated) and it has no opening anchor yet, Account#opening_anchor_date+ # falls back to (oldest entry date - 1 day), which can itself land in the+ # future. Without the clamp, calc_start_date would exceed calc_end_date+ # (which never extends past today -- see Balance::ForwardCalculator) and the+ # calculation would silently produce zero balance rows instead of a+ # Date.current baseline.def calculation_start_date- @calculation_start_date ||= [ account.opening_anchor_date, account.entries.excluding_pending.minimum(:date) ].compact.min+ @calculation_start_date ||= [ account.opening_anchor_date, account.entries.excluding_pending.minimum(:date), Date.current ].compact.minendprivatediff --git a/app/models/balance/forward_calculator.rb b/app/models/balance/forward_calculator.rbindex b0d0a135ea..45c5e5fd2f 100644--- a/app/models/balance/forward_calculator.rb+++ b/app/models/balance/forward_calculator.rb@@ -139,7 +139,11 @@ class Balance::ForwardCalculator < Balance::BaseCalculatorenddef calc_end_date- [ account.entries.excluding_pending.maximum(:date), account.holdings.maximum(:date) ].compact.max || Date.current+ # Scheduled (future-dated) entries must not extend the calculation window --+ # otherwise their flows would materialize a balance dated in the future,+ # and Balance::Materializer#update_account_info would surface that as the+ # account's *current* balance. See Entry#scheduled? and Balance::SyncCache.+ [ account.entries.excluding_pending.where(date: ..Date.current).maximum(:date), account.holdings.maximum(:date) ].compact.max || Date.currentend# Negative entries amount on an "asset" account means, "account value has increased"diff --git a/app/models/balance/materializer.rb b/app/models/balance/materializer.rbindex 8d9f9f1112..596ffc4ad3 100644--- a/app/models/balance/materializer.rb+++ b/app/models/balance/materializer.rb@@ -35,9 +35,15 @@ class Balance::Materializerenddef update_account_info- # Query fresh balance from DB to get generated column values+ # Query fresh balance from DB to get generated column values.+ # Excludes future-dated rows defensively: purge_stale_balances should+ # already remove any balance row beyond the freshly calculated range,+ # but if a scheduled (future-dated) row ever survives (e.g. a race+ # between overlapping incremental syncs), account.balance must never+ # surface it as the *current* balance. See Entry#scheduled?.current_balance = account.balances.where(currency: account.currency)+ .where(date: ..Date.current).order(date: :desc).firstdiff --git a/app/models/balance/sync_cache.rb b/app/models/balance/sync_cache.rbindex f2d9ae06cd..9dfd1cabb9 100644--- a/app/models/balance/sync_cache.rb+++ b/app/models/balance/sync_cache.rb@@ -74,6 +74,10 @@ class Balance::SyncCacheenddef converted_entries+ # Scheduled (future-dated) entries are excluded from balance calculations+ # entirely -- they must not affect the account's current balance until+ # their date arrives. A daily sync naturally picks them up once "today"+ # reaches their date (see Entry#scheduled?).@converted_entries ||= beginmissing_rate_pairs = []@@ -119,7 +123,7 @@ class Balance::SyncCacheenddef entries_scope- scope = account.entries.excluding_pending.excluding_split_parents.includes(:entryable).order(:date)+ scope = account.entries.excluding_pending.excluding_split_parents.where(date: ..Date.current).includes(:entryable).order(:date)@start_date ? scope.where(date: @start_date..) : scopeenddiff --git a/app/models/entry.rb b/app/models/entry.rbindex f9b1ebc6af..00a1d9117a 100644--- a/app/models/entry.rb+++ b/app/models/entry.rb@@ -115,6 +115,11 @@ class Entry < ApplicationRecordSQL}+ # Future-dated entries haven't happened yet, so "actual" reporting (budgets,+ # income statement, insights) should not count them until their date+ # arrives -- see Entry#scheduled?.+ scope :excluding_scheduled, -> { where("entries.date <= ?", Date.current) }+# Find stale pending transactions (pending for more than X days with no matching posted version)scope :stale_pending, ->(days: 8) {pending.where("entries.date < ?", days.days.ago.to_date)@@ -340,6 +345,8 @@ class Entry < ApplicationRecordsync_start_date = [ @earliest_saved_date, date_previously_was, date ].compact.min unless destroyed?@earliest_saved_date = nilaccount.sync_later(window_start_date: sync_start_date)++ EntryScheduledSyncJob.schedule_for(self) if !destroyed? && scheduled?end# Whether the last save changed anything a sync depends on. Call it right@@ -382,6 +389,14 @@ class Entry < ApplicationRecordexternal_id.present?end+ # A manually entered entry dated after today (e.g. an upcoming bill or+ # expected paycheck). Scheduled entries are excluded from balance+ # calculations until their date arrives -- see Balance::SyncCache and+ # Balance::ForwardCalculator#calc_end_date.+ def scheduled?+ date > Date.current+ end+# Reconciliation state, following the Quicken uncleared / cleared / reconciled# model. Only the last state is stored -- see AddReconciliationToEntries.#@@ -654,6 +669,10 @@ class Entry < ApplicationRecordreturn 0 unless has_updates+ # account_id => earliest of old/new date, for entries whose date moved+ sync_windows = {}+ rescheduled_ids = []+transaction doall.each do |entry|changed = false@@ -670,6 +689,12 @@ class Entry < ApplicationRecordentry.update! attrsentry.transaction.record_category_usage! if entry.transaction?changed = true++ if entry.saved_change_to_date?+ window_start = entry.saved_change_to_date.compact.min+ sync_windows[entry.account] = [ sync_windows[entry.account], window_start ].compact.min+ rescheduled_ids << entry.id+ endendend@@ -688,6 +713,11 @@ class Entry < ApplicationRecordendend+ # Moving a date changes balances (and may make an entry scheduled), so+ # mirror Entry#sync_account_later -- once per account, not per entry.+ sync_windows.each { |account, window_start| account.sync_later(window_start_date: window_start) }+ EntryScheduledSyncJob.schedule_for_entries(Entry.where(id: rescheduled_ids)) if rescheduled_ids.any?+all.sizeendenddiff --git a/app/models/family.rb b/app/models/family.rbindex a6355e797c..4a71947c26 100644--- a/app/models/family.rb+++ b/app/models/family.rb@@ -894,7 +894,53 @@ class Family < ApplicationRecordRails.application.message_verifier("bills-user-feed")end+ # The family's timezone, validated and with a safe fallback -- used both by+ # `Localize#switch_timezone` (request path) and `Sync#perform` (background+ # path), so a scheduled entry's "has it arrived yet?" check (Entry#scheduled?)+ # agrees with the family's own clock in both places instead of silently+ # defaulting to the app's zone (UTC) only in the background.+ #+ # `timezone` is a free-text IANA name (e.g. from an older DB dump, or a zone+ # the tzdata maintainers later renamed, like the historical "Europe/Kiev" ->+ # "Europe/Kyiv" switch), so this re-validates rather than trusting the+ # column -- see `timezone_must_be_a_known_zone` below.+ def resolved_time_zone+ return Time.zone if timezone.blank?++ zone = ActiveSupport::TimeZone[timezone]+ return zone if zone.present?++ log_invalid_timezone_once+ Time.zone+ end++ # How often to write a DebugLogEntry for the same (family, bad value)+ # pair. `resolved_time_zone` runs on every request and every sync, so+ # without this an affected family would write one row per call forever.+ INVALID_TIMEZONE_LOG_INTERVAL = 1.day+ private_constant :INVALID_TIMEZONE_LOG_INTERVAL+private++ def log_invalid_timezone_once+ cache_key = [ "invalid_family_timezone", id, timezone ]++ # `fetch` is read-then-write, not atomic -- two concurrent+ # requests/jobs could both see a miss and both log. `write(unless_exist:+ # true)` maps to Redis's atomic SET NX in production, so only one ever+ # wins the lease and logs.+ lease_acquired = Rails.cache.write(cache_key, true, expires_in: INVALID_TIMEZONE_LOG_INTERVAL, unless_exist: true)+ return unless lease_acquired++ DebugLogEntry.capture(+ category: "other",+ level: "warn",+ message: "Invalid family timezone #{timezone.inspect}, falling back to #{Time.zone.name}",+ source: "Family#resolved_time_zone",+ family: self+ )+ end+# Bayes first, so the matcher lands above it.def add_classifier_rulesCLASSIFIER_ACTION_TYPES.reverse_each { |action_type| add_classifier_rule!(action_type) }diff --git a/app/models/import.rb b/app/models/import.rbindex e0a38a7833..f93e0a262c 100644--- a/app/models/import.rb+++ b/app/models/import.rb@@ -289,6 +289,7 @@ class Import < ApplicationRecordimport!family.sync_later+ EntryScheduledSyncJob.schedule_for_entries(entries)update! status: :completerescue => errordiff --git a/app/models/import_session.rb b/app/models/import_session.rbindex c6b6677817..0daa0abd5a 100644--- a/app/models/import_session.rb+++ b/app/models/import_session.rb@@ -270,6 +270,7 @@ class ImportSession < ApplicationRecordupdate!(status: :complete, summary: aggregate_chunk_summaries, error_details: {})enqueue_family_sync+ EntryScheduledSyncJob.schedule_for_entries(Entry.where(import_id: imports.select(:id)))Rails.logger.info("ImportSession publish completed import_session_id=#{id}")rescue => errorupdate!(diff --git a/app/models/income_statement.rb b/app/models/income_statement.rbindex 1dec491a68..3b726d6698 100644--- a/app/models/income_statement.rb+++ b/app/models/income_statement.rb@@ -20,7 +20,7 @@ class IncomeStatementdef totals(transactions_scope: nil, date_range:)# Default to excluding pending transactions from budget/analytics calculations# Pending transactions shouldn't affect budget totals until they post- transactions_scope ||= family.transactions.visible.excluding_pending+ transactions_scope ||= family.transactions.visible.excluding_pending.merge(Entry.excluding_scheduled)result = totals_query(transactions_scope: transactions_scope, date_range: date_range)@@ -151,7 +151,7 @@ class IncomeStatementenddef totals_for(period, account_ids: nil)- scope = family.transactions.visible.excluding_pending.in_period(period)+ scope = family.transactions.visible.excluding_pending.merge(Entry.excluding_scheduled).in_period(period)scope = scope.where(entries: { account_id: account_ids }) if account_ids.present?totals(transactions_scope: scope, date_range: period.date_range)@@ -257,7 +257,7 @@ class IncomeStatement@totals_for_period ||= {}@totals_for_period[period_cache_key(period)] ||=totals_query(- transactions_scope: family.transactions.visible.excluding_pending.in_period(period),+ transactions_scope: family.transactions.visible.excluding_pending.merge(Entry.excluding_scheduled).in_period(period),date_range: period.date_range)end@@ -270,7 +270,7 @@ class IncomeStatement]) doDailyExpenseTotals.new(family,- transactions_scope: family.transactions.visible.excluding_pending.in_period(period),+ transactions_scope: family.transactions.visible.excluding_pending.merge(Entry.excluding_scheduled).in_period(period),date_range: period.date_range,included_account_ids: included_account_ids).call@@ -290,7 +290,7 @@ class IncomeStatement]) doDailyExpenseTotals.new(family,- transactions_scope: family.transactions.visible.excluding_pending.in_period(period),+ transactions_scope: family.transactions.visible.excluding_pending.merge(Entry.excluding_scheduled).in_period(period),date_range: period.date_range,included_account_ids: included_account_ids,by_category: true@@ -341,9 +341,11 @@ class IncomeStatement# An IncomeStatement is a request-scoped reporting snapshot, like its memoized# period totals. Share these aggregate reads across totals and daily series.# Rates, target currency and whether investing counts as spending can- # change without touching entries or accounts.+ # change without touching entries or accounts. Scheduled entries are+ # excluded as of "today", so the key also rolls over daily.def cache_freshness_key@cache_freshness_key ||= [+ Date.current,family.entries_cache_version,family.accounts_status_version,family.currency,diff --git a/app/models/income_statement/category_stats.rb b/app/models/income_statement/category_stats.rbindex 6df45689e0..4530e7b71e 100644--- a/app/models/income_statement/category_stats.rb+++ b/app/models/income_statement/category_stats.rb@@ -54,6 +54,7 @@ class IncomeStatement::CategoryStats#{pending_providers_sql}#{exclude_tax_advantaged_sql}#{scope_to_account_ids_sql}+ #{excluding_scheduled_sql}GROUP BY c.id, period, #{classification_sql("t")})SELECTdiff --git a/app/models/income_statement/family_stats.rb b/app/models/income_statement/family_stats.rbindex ebdc289ca3..f63df617ad 100644--- a/app/models/income_statement/family_stats.rb+++ b/app/models/income_statement/family_stats.rb@@ -51,6 +51,7 @@ class IncomeStatement::FamilyStats#{pending_providers_sql}#{exclude_tax_advantaged_sql}#{scope_to_account_ids_sql}+ #{excluding_scheduled_sql}GROUP BY period, #{classification_sql("t")})SELECTdiff --git a/app/models/income_statement/scoped_transactions_query.rb b/app/models/income_statement/scoped_transactions_query.rbindex 5c95de04df..d18bb64597 100644--- a/app/models/income_statement/scoped_transactions_query.rb+++ b/app/models/income_statement/scoped_transactions_query.rb@@ -64,6 +64,17 @@ module IncomeStatement::ScopedTransactionsQueryTransaction.pending_providers_sql(t)end+ # Scheduled (future-dated) entries haven't happened yet, so "actual"+ # reporting shouldn't count them -- see Entry#excluding_scheduled. Only+ # needed by the queries here that build their own SQL directly against+ # `transactions`/`entries` (FamilyStats, CategoryStats); Totals and+ # DailyExpenseTotals instead select from a caller-supplied+ # `transactions_scope`, which already carries this exclusion (see+ # IncomeStatement#totals/#totals_for_period).+ def excluding_scheduled_sql+ "AND ae.date <= :today"+ end+# Tax-advantaged accounts (401k, IRA, HSA, etc.) are retirement savings,# not daily expenses, so they're excluded from budget calculations.def exclude_tax_advantaged_sql@@ -87,7 +98,7 @@ module IncomeStatement::ScopedTransactionsQuery# Bind params every income statement query needs; classes merge their# extras (date range, interval, account ids) on top.def base_sql_params(extra = {})- { target_currency: @family.currency, family_id: @family.id }.merge(extra).tap do |params|+ { target_currency: @family.currency, family_id: @family.id, today: Date.current }.merge(extra).tap do |params|ids = @family.tax_advantaged_account_idsparams[:tax_advantaged_account_ids] = ids if ids.present?enddiff --git a/app/models/sync.rb b/app/models/sync.rbindex 310c43e55b..66079a2a4e 100644--- a/app/models/sync.rb+++ b/app/models/sync.rb@@ -177,45 +177,52 @@ class Sync < ApplicationRecordenddef perform- Rails.logger.tagged("Sync", id, syncable_type, syncable_id) do- # This can happen on server restarts or if Sidekiq enqueues a duplicate job- unless may_start?- Rails.logger.warn("Sync #{id} is not in a valid state (#{aasm.from_state}) to start. Skipping sync.")- return- end+ # Entry#scheduled?, Balance::SyncCache and Balance::ForwardCalculator all+ # key off Date.current -- without this, a job worker (no request, no+ # Localize#switch_timezone) runs them in the app's default zone (UTC),+ # not the family's, so a scheduled entry can materialize hours early or+ # late around midnight depending on the family's offset from UTC.+ Time.use_zone(family&.resolved_time_zone || Time.zone) do+ Rails.logger.tagged("Sync", id, syncable_type, syncable_id) do+ # This can happen on server restarts or if Sidekiq enqueues a duplicate job+ unless may_start?+ Rails.logger.warn("Sync #{id} is not in a valid state (#{aasm.from_state}) to start. Skipping sync.")+ next+ end- # Guard: syncable may have been deleted while job was queued- unless syncable.present?- Rails.logger.warn("Sync #{id} - syncable #{syncable_type}##{syncable_id} no longer exists. Marking as failed.")- start! if may_start?- fail! if may_fail?- update(error: "Syncable record was deleted")- return- end+ # Guard: syncable may have been deleted while job was queued+ unless syncable.present?+ Rails.logger.warn("Sync #{id} - syncable #{syncable_type}##{syncable_id} no longer exists. Marking as failed.")+ start! if may_start?+ fail! if may_fail?+ update(error: "Syncable record was deleted")+ next+ end- # Guard: syncable may be scheduled for deletion- if syncable.respond_to?(:scheduled_for_deletion?) && syncable.scheduled_for_deletion?- Rails.logger.warn("Sync #{id} - syncable #{syncable_type}##{syncable_id} is scheduled for deletion. Skipping sync.")- start! if may_start?- fail! if may_fail?- update(error: "Syncable record is scheduled for deletion")- return- end+ # Guard: syncable may be scheduled for deletion+ if syncable.respond_to?(:scheduled_for_deletion?) && syncable.scheduled_for_deletion?+ Rails.logger.warn("Sync #{id} - syncable #{syncable_type}##{syncable_id} is scheduled for deletion. Skipping sync.")+ start! if may_start?+ fail! if may_fail?+ update(error: "Syncable record is scheduled for deletion")+ next+ end- start!-- begin- syncable.perform_sync(self)- rescue => e- # Re-check state under a row lock (with_lock reloads): the sync may- # have been terminalized externally (marked stale by SyncCleanerJob)- # while this job was still running. An unguarded fail! on the in-memory- # record would silently overwrite that terminal status.- with_lock { fail! if may_fail? }- update(error: e.message)- report_error(e)- ensure- finalize_if_all_children_finalized+ start!++ begin+ syncable.perform_sync(self)+ rescue => e+ # Re-check state under a row lock (with_lock reloads): the sync may+ # have been terminalized externally (marked stale by SyncCleanerJob)+ # while this job was still running. An unguarded fail! on the in-memory+ # record would silently overwrite that terminal status.+ with_lock { fail! if may_fail? }+ update(error: e.message)+ report_error(e)+ ensure+ finalize_if_all_children_finalized+ endendendenddiff --git a/app/models/transaction/search.rb b/app/models/transaction/search.rbindex cb4608fcba..2c541e332f 100644--- a/app/models/transaction/search.rb+++ b/app/models/transaction/search.rb@@ -207,8 +207,26 @@ class Transaction::Search# the old logic would keep being served (same cache_key_base) after# deploy, disagreeing with the (uncached) transactions_scope list# until entries_cache_version next changes for that family.- Rails.cache.fetch("transaction_search_totals/v3/#{cache_key_base}") do+ # v4: Totals gained excluded_scheduled_count.+ Rails.cache.fetch("transaction_search_totals/v4/#{cache_key_base}") doscope = transactions_scope+ excluded_scheduled_count = 0++ # Exclude scheduled (future-dated) entries from totals by default -- they+ # haven't happened yet, so they shouldn't count toward this period's+ # income/expenses (see Entry#scheduled?). An explicit end_date filter, or+ # a start_date after today, is a deliberate request to look ahead (e.g.+ # "next 30 days", "everything from next month"), so it's left untouched+ # in that case.+ #+ # The list still shows them, so count how many were left out -- the+ # summary uses it to say how many of the listed rows are scheduled.+ # (Tax-advantaged accounts, filtered below, also stay out of the+ # money figures; this count deliberately ignores that.)+ unless look_ahead?+ excluded_scheduled_count = scope.where("entries.date > ?", Date.current).count+ scope = scope.where("entries.date <= ?", Date.current)+ end# Exclude tax-advantaged accounts from totals calculationtax_advantaged_ids = family.tax_advantaged_account_ids@@ -244,6 +262,7 @@ class Transaction::SearchTotals.new(count: result&.transactions_count.to_i,+ excluded_scheduled_count: excluded_scheduled_count,income_money: Money.new((result&.income_total || 0), family.currency),expense_money: Money.new((result&.expense_total || 0), family.currency),transfer_inflow_money: Money.new((result&.transfer_inflow_total || 0), family.currency),@@ -261,12 +280,21 @@ class Transaction::SearchDigest::SHA256.hexdigest(attributes.sort.to_h.to_json), # cached by filtersfamily.entries_cache_version,Digest::SHA256.hexdigest(family.tax_advantaged_account_ids.sort.to_json), # stable across processes- accessible_account_ids ? Digest::SHA256.hexdigest(accessible_account_ids.sort.to_json) : "all"+ accessible_account_ids ? Digest::SHA256.hexdigest(accessible_account_ids.sort.to_json) : "all",+ Date.current # totals exclude scheduled entries as of "today" -- must roll over daily].join("/")endprivate- Totals = Data.define(:count, :income_money, :expense_money, :transfer_inflow_money, :transfer_outflow_money)+ Totals = Data.define(:count, :excluded_scheduled_count, :income_money, :expense_money, :transfer_inflow_money, :transfer_outflow_money)++ def look_ahead?+ return true if end_date.present?++ start_date.present? && Date.parse(start_date.to_s) > Date.current+ rescue Date::Error+ false+ end# Filter query to include only active accounts if requesteddef apply_active_accounts_filter(query, active_accounts_only_filter)diff --git a/app/models/transfer/creator.rb b/app/models/transfer/creator.rbindex 90ee290d2b..6b203756e2 100644--- a/app/models/transfer/creator.rb+++ b/app/models/transfer/creator.rb@@ -63,8 +63,7 @@ class Transfer::Creatorapply_tags!(transfer) if tag_ids.any?end- source_account.sync_later- destination_account.sync_later+ transfer.sync_account_latertransferrescue ActiveRecord::RecordNotUniquediff --git a/app/views/accounts/_scheduled_balance_tooltip.html.erb b/app/views/accounts/_scheduled_balance_tooltip.html.erbnew file mode 100644index 0000000000..195d4cac86--- /dev/null+++ b/app/views/accounts/_scheduled_balance_tooltip.html.erb@@ -0,0 +1,34 @@+<%# locals: (account:) %>++<%= render DS::Tooltip.new(placement: "right", offset: 10, cross_axis: 50) do %>+ <div>+ <%= t(".description") %>+ </div>+ <div class="flex pt-3">+ <div class="opacity-70">+ <%= t(".current") %>+ </div>+ <div class="ml-auto privacy-sensitive">+ <%= format_money(account.balance_money, precision: 0) %>+ </div>+ </div>+ <div class="flex">+ <div class="opacity-70">+ <%= t(".scheduled") %>+ </div>+ <div class="ml-auto privacy-sensitive">+ <%= "#{'+' if account.scheduled_entries_total_money.amount.positive?}#{format_money(account.scheduled_entries_total_money, precision: 0)}" %>+ </div>+ </div>++ <hr class="my-2 border-inverse">++ <div class="flex">+ <div class="font-bold opacity-70">+ <%= t(".projected") %>+ </div>+ <div class="font-bold ml-auto privacy-sensitive">+ <%= format_money(account.projected_balance_money, precision: 0) %>+ </div>+ </div>+<% end %>diff --git a/app/views/investments/_value_tooltip.html.erb b/app/views/investments/_value_tooltip.html.erbindex 510c41acd4..1ab88583b9 100644--- a/app/views/investments/_value_tooltip.html.erb+++ b/app/views/investments/_value_tooltip.html.erb@@ -1,4 +1,4 @@-<%# locals: (balance:, holdings:, cash:) %>+<%# locals: (balance:, holdings:, cash:, scheduled: nil, projected: nil) %><div data-controller="tooltip" data-tooltip-placement-value="right" data-tooltip-offset-value=10 data-tooltip-cross-axis-value=50><%= icon("info", size: "sm") %>@@ -33,5 +33,27 @@<%= tag.p format_money(balance, precision: 0) %></div></div>++ <% if scheduled %>+ <div class="flex">+ <div class="text-inverse opacity-70">+ <%= t(".scheduled") %>+ </div>+ <div class="text-inverse ml-auto privacy-sensitive">+ <%= tag.p "#{'+' if scheduled.amount.positive?}#{format_money(scheduled, precision: 0)}" %>+ </div>+ </div>++ <hr class="my-2 border-inverse">++ <div class="flex">+ <div class="text-inverse opacity-70">+ <%= t(".projected") %>+ </div>+ <div class="text-inverse font-bold ml-auto privacy-sensitive">+ <%= tag.p format_money(projected, precision: 0) %>+ </div>+ </div>+ <% end %></div></div>diff --git a/app/views/trades/_trade.html.erb b/app/views/trades/_trade.html.erbindex 95ac57d868..c907c5ee34 100644--- a/app/views/trades/_trade.html.erb+++ b/app/views/trades/_trade.html.erb@@ -46,6 +46,18 @@data: { turbo_frame: "drawer", turbo_prefetch: false, clickable_row_target: "link" },class: "hover:underline" %></div>++ <% if entry.scheduled? %>+ <div class="flex items-center gap-1 flex-shrink-0">+ <%= render DS::Pill.new(+ label: t("trades.trade.scheduled"),+ tone: :neutral,+ marker: false,+ icon: "calendar"+ ) %>+ <%= render DS::Tooltip.new(text: t("trades.trade.scheduled_tooltip"), as: :span) %>+ </div>+ <% end %><% end %></div></div>@@ -64,6 +76,7 @@<%= icon "lock", size: "sm", class: "text-secondary" %><% end %><% end %>+<%= content_tag :p,format_money(-entry.amount_money),class: ["privacy-sensitive", "text-green-600": entry.amount.negative?] %>diff --git a/app/views/trades/show.html.erb b/app/views/trades/show.html.erbindex 7fe0772fdb..c7eb478221 100644--- a/app/views/trades/show.html.erb+++ b/app/views/trades/show.html.erb@@ -26,7 +26,6 @@data: { controller: "auto-submit-form" } do |f| %><%= f.date_field :date,label: t(".date_label"),- max: Date.current,disabled: @entry.linked?,"data-auto-submit-form-target": "auto" %><% if trade.qty.zero? %>diff --git a/app/views/transactions/_form.html.erb b/app/views/transactions/_form.html.erbindex ad31ff6821..46f168ce32 100644--- a/app/views/transactions/_form.html.erb+++ b/app/views/transactions/_form.html.erb@@ -65,7 +65,6 @@label: t(".date"),required: true,min: Entry.min_supported_date,- max: Date.current,value: f.object.date || Date.current,data: { transaction_form_target: "date", action: "change->transaction-form#checkCurrencyDifference" } %>diff --git a/app/views/transactions/_summary.html.erb b/app/views/transactions/_summary.html.erbindex b77853cc79..8fa77b110d 100644--- a/app/views/transactions/_summary.html.erb+++ b/app/views/transactions/_summary.html.erb@@ -1,4 +1,4 @@-<%# locals: (totals:) %>+<%# locals: (totals:, transactions_count:) %><%# Show Inflow/Outflow labels only when the result set contains exclusively transfers(income and expense are both $0). For mixed filters (e.g. Expense+Transfer),we keep Income/Expenses labels — transfer amounts aren't included in the summary@@ -8,7 +8,10 @@<div class="grid grid-cols-1 md:grid-cols-3 bg-container rounded-xl shadow-border-xs md:divide-x divide-y md:divide-y-0 divide-alpha-black-100 theme-dark:divide-alpha-white-200"><div class="p-4 space-y-2"><p class="text-sm text-secondary"><%= t("transactions.summary.total_transactions") %></p>- <p class="text-primary font-medium text-xl privacy-sensitive" id="total-transactions"><%= totals.count.round(0) %></p>+ <p class="text-primary font-medium text-xl privacy-sensitive" id="total-transactions"><%= transactions_count %></p>+ <% if totals.excluded_scheduled_count.positive? %>+ <p class="text-xs text-secondary" id="scheduled-transactions-count"><%= t("transactions.summary.scheduled_count", count: totals.excluded_scheduled_count) %></p>+ <% end %></div><div class="p-4 space-y-2"><% if show_transfers %>diff --git a/app/views/transactions/_transaction.html.erb b/app/views/transactions/_transaction.html.erbindex 8f449888e0..da77dfe2b1 100644--- a/app/views/transactions/_transaction.html.erb+++ b/app/views/transactions/_transaction.html.erb@@ -97,6 +97,17 @@</span><% end %>+ <%# Scheduled (future-dated) indicator %>+ <% if entry.scheduled? %>+ <%= render DS::Pill.new(+ label: t("transactions.transaction.scheduled"),+ tone: :neutral,+ marker: false,+ icon: "calendar"+ ) %>+ <%= render DS::Tooltip.new(text: t("transactions.transaction.scheduled_tooltip"), as: :span) %>+ <% end %>+<%# Potential duplicate indicator - different styling for low vs medium confidence %><% if transaction.has_potential_duplicate? %><% if transaction.low_confidence_duplicate? %>diff --git a/app/views/transactions/bulk_updates/new.html.erb b/app/views/transactions/bulk_updates/new.html.erbindex df7d55b37c..5b8f090583 100644--- a/app/views/transactions/bulk_updates/new.html.erb+++ b/app/views/transactions/bulk_updates/new.html.erb@@ -5,7 +5,7 @@<%= styled_form_with url: transactions_bulk_update_path, scope: "bulk_update", class: "h-full flex flex-col justify-between gap-4", data: { turbo_frame: "_top" } do |form| %><div class="space-y-4"><%= render DS::Disclosure.new(title: t(".overview"), open: true) do %>- <%= form.date_field :date, label: t(".date_label"), max: Date.current %>+ <%= form.date_field :date, label: t(".date_label") %><% end %><%= render DS::Disclosure.new(title: t(".transactions_section"), open: true) do %>diff --git a/app/views/transactions/index.html.erb b/app/views/transactions/index.html.erbindex 49f68c131a..54c7bc463f 100644--- a/app/views/transactions/index.html.erb+++ b/app/views/transactions/index.html.erb@@ -48,7 +48,7 @@</div></header>- <%= render "summary", totals: @search.totals %>+ <%= render "summary", totals: @search.totals, transactions_count: @pagy.count %><% if Current.family.recurring_transactions_disabled? %><%= render "transactions/list", transactions: @transactions, projected_recurring: @projected_recurring, q: params[:q], pagy: @pagy %><% else %>diff --git a/app/views/transactions/show.html.erb b/app/views/transactions/show.html.erbindex d3b15eee74..c121f709cd 100644--- a/app/views/transactions/show.html.erb+++ b/app/views/transactions/show.html.erb@@ -65,7 +65,6 @@"data-auto-submit-form-target": "auto" %><%= f.date_field :date,label: t(".date_label"),- max: Date.current,disabled: @entry.linked? || split_locked || edit_locked,"data-auto-submit-form-target": "auto" %><% unless @entry.transaction.transfer? %>diff --git a/app/views/transfers/_form.html.erb b/app/views/transfers/_form.html.erbindex 862ac1adca..31306eafd8 100644--- a/app/views/transfers/_form.html.erb+++ b/app/views/transfers/_form.html.erb@@ -37,7 +37,7 @@<%= f.collection_select :from_account_id, @accounts, :id, :name, { prompt: t(".select_account"), label: t(".from"), selected: @from_account_id, variant: :logo, searchable: true }, { required: true, data: { transfer_form_target: "fromAccount", action: "change->transfer-form#checkCurrencyDifference" } } %><%= f.collection_select :to_account_id, @accounts, :id, :name, { prompt: t(".select_account"), label: t(".to"), variant: :logo, searchable: true }, { required: true, data: { transfer_form_target: "toAccount", action: "change->transfer-form#checkCurrencyDifference" } } %>- <%= f.date_field :date, value: transfer.inflow_transaction&.entry&.date || Date.current, label: t(".date"), required: true, max: Date.current, data: { transfer_form_target: "date", action: "change->transfer-form#checkCurrencyDifference" } %>+ <%= f.date_field :date, value: transfer.inflow_transaction&.entry&.date || Date.current, label: t(".date"), required: true, data: { transfer_form_target: "date", action: "change->transfer-form#checkCurrencyDifference" } %><%= f.number_field :amount, label: t(".source_amount"), required: true, min: 0, placeholder: "100", step: 0.00000001, data: { transfer_form_target: "amount", action: "input->transfer-form#onSourceAmountChange" } %>diff --git a/config/locales/views/accounts/en.yml b/config/locales/views/accounts/en.ymlindex 51bb643f0c..debd1d32ad 100644--- a/config/locales/views/accounts/en.yml+++ b/config/locales/views/accounts/en.yml@@ -6,6 +6,11 @@ en:success: "Entry deleted successfully."accounts:not_authorized: "You don't have permission to manage this account"+ scheduled_balance_tooltip:+ description: Your balance once all scheduled transactions have posted+ current: Current balance+ scheduled: Scheduled+ projected: Projected balanceaccount:complete_setup: Complete setupedit: Editdiff --git a/config/locales/views/accounts/fr.yml b/config/locales/views/accounts/fr.ymlindex cb0df873c2..2d10e3732f 100644--- a/config/locales/views/accounts/fr.yml+++ b/config/locales/views/accounts/fr.yml@@ -5,6 +5,11 @@ fr:destroy:success: Entrée supprimée avec succès.accounts:+ scheduled_balance_tooltip:+ description: Votre solde une fois toutes les transactions planifiées validées+ current: Solde actuel+ scheduled: Planifié+ projected: Solde prévisionnelaccount:change_simplefin_account: Changer le compte SimpleFINcomplete_setup: Configuration complètediff --git a/config/locales/views/components/en.yml b/config/locales/views/components/en.ymlindex bd98a16daf..350074206a 100644--- a/config/locales/views/components/en.yml+++ b/config/locales/views/components/en.yml@@ -107,6 +107,8 @@ en:activity_date:balance_tooltip: "The end of day balance, after all transactions and adjustments"no_balance_data: "No balance data available for this date"+ projected: "Projected"+ projected_balance_tooltip: "An estimate: current balance plus scheduled entries through this date"ds:alert:variants:diff --git a/config/locales/views/components/fr.yml b/config/locales/views/components/fr.ymlindex 672f7c738f..800fbdbfdb 100644--- a/config/locales/views/components/fr.yml+++ b/config/locales/views/components/fr.yml@@ -5,6 +5,8 @@ fr:activity_date:balance_tooltip: Le solde de fin de journée, après toutes les transactions et ajustementsno_balance_data: Aucune donnée de solde disponible pour cette date+ projected: Prévisionnel+ projected_balance_tooltip: "Une estimation : solde actuel plus les entrées planifiées jusqu'à cette date"activity_feed:toggle_selection_checkboxes: Basculer la sélectionbalance_reconciliation:diff --git a/config/locales/views/investments/en.yml b/config/locales/views/investments/en.ymlindex 2ce135a42b..012ab27367 100644--- a/config/locales/views/investments/en.yml+++ b/config/locales/views/investments/en.yml@@ -198,6 +198,8 @@ en:value_tooltip:cash: Cashholdings: Holdings+ projected: Projected balance+ scheduled: Scheduledtotal: Portfolio balancetotal_value_tooltip: The total portfolio balance is the sum of brokerage cash(available for trading) and the current market value of your holdings.diff --git a/config/locales/views/investments/fr.yml b/config/locales/views/investments/fr.ymlindex 1842ab8159..957b434d05 100644--- a/config/locales/views/investments/fr.yml+++ b/config/locales/views/investments/fr.yml@@ -188,6 +188,8 @@ fr:value_tooltip:cash: Liquiditésholdings: Titres+ projected: Solde prévisionnel+ scheduled: Planifiétotal: Valeur totale du portefeuilletotal_value_tooltip: Le solde total du portefeuille correspond à la somme desliquidités (disponibles pour la négociation) et de la valeur marchande actuellediff --git a/config/locales/views/trades/en.yml b/config/locales/views/trades/en.ymlindex 00200ba7e2..fe50d3a749 100644--- a/config/locales/views/trades/en.yml+++ b/config/locales/views/trades/en.yml@@ -26,6 +26,9 @@ en:type_interest: Interestdividend_requires_security: Security is required for dividendstrade_requires_security: A security (ticker) is required for buy and sell trades+ trade:+ scheduled: Scheduled+ scheduled_tooltip: Dated in the future — won't affect your balance until thenheader:buy: Buysell: Selldiff --git a/config/locales/views/trades/fr.yml b/config/locales/views/trades/fr.ymlindex 6e17c61954..ab2746b9d1 100644--- a/config/locales/views/trades/fr.yml+++ b/config/locales/views/trades/fr.yml@@ -26,6 +26,9 @@ fr:type_interest: Intérêtstype_sell: Vendretype_withdrawal: Retrait+ trade:+ scheduled: Planifiée+ scheduled_tooltip: Datée dans le futur — n'affectera votre solde qu'à cette dateheader:buy: Achetercontribution: Contributiondiff --git a/config/locales/views/transactions/en.yml b/config/locales/views/transactions/en.ymlindex 816bc80ea7..4a63de96bc 100644--- a/config/locales/views/transactions/en.yml+++ b/config/locales/views/transactions/en.yml@@ -185,6 +185,8 @@ en:potential_duplicate_tooltip: This may be a duplicate of another transactionreview_recommended: Reviewreview_recommended_tooltip: Large amount difference — review recommended to check if this is a duplicate+ scheduled: Scheduled+ scheduled_tooltip: Dated in the future — won't affect your balance until thensplit: Splitsplit_tooltip: This transaction has been split into multiple entriessplit_child_tooltip: Part of a split transaction@@ -207,6 +209,9 @@ en:reject_title: Keep as separate transactionssummary:total_transactions: Total transactions+ scheduled_count:+ one: "including %{count} scheduled"+ other: "including %{count} scheduled"income: Incomeexpenses: Expensesinflow: Inflowdiff --git a/config/locales/views/transactions/fr.yml b/config/locales/views/transactions/fr.ymlindex 3adf8721e8..137df14cf1 100644--- a/config/locales/views/transactions/fr.yml+++ b/config/locales/views/transactions/fr.yml@@ -373,6 +373,9 @@ fr:income: Revenusinflow: Entréesoutflow: Sorties+ scheduled_count:+ one: dont %{count} planifiée+ other: dont %{count} planifiéestotal_transactions: Total des transactionstoggle_recurring_section: Afficher/masquer les transactions récurrentes à venirtransaction:@@ -384,6 +387,8 @@ fr:potential_duplicate_tooltip: Cette transaction peut être un doublon d'une autre transactionreview_recommended: Vérifierreview_recommended_tooltip: Écart de montant important — vérification recommandée pour vérifier s'il s'agit d'un doublon+ scheduled: Planifiée+ scheduled_tooltip: Datée dans le futur — n'affectera votre solde qu'à cette datesplit: Fractionnersplit_child_tooltip: Partie d'une transaction fractionnéesplit_tooltip: Cette transaction a été fractionnée en plusieurs entréesdiff --git a/test/components/UI/account/activity_date_test.rb b/test/components/UI/account/activity_date_test.rbnew file mode 100644index 0000000000..fad713ab5e--- /dev/null+++ b/test/components/UI/account/activity_date_test.rb@@ -0,0 +1,82 @@+require "test_helper"++class UI::Account::ActivityDateTest < ViewComponent::TestCase+ setup do+ Current.session = sessions(:one)+ end++ test "shows the projected balance and marks it as such for a scheduled date" do+ account = accounts(:depository)+ projected = Money.new(5300, account.currency)++ data = Account::ActivityFeedData::ActivityDateData.new(+ date: Date.current + 5.days,+ entries: [],+ balance: nil,+ projected_balance_money: projected,+ transfers: [],+ split_parents: {}+ )++ component = UI::Account::ActivityDate.new(account: account, data: data)++ assert_equal projected, component.end_balance_money+ assert component.projected?++ render_inline(component)++ # Guards against translations silently missing under the wrong i18n+ # scope -- a missing key renders humanized text wrapped in a+ # "translation_missing" span, which also breaks DS::Pill's `title`+ # attribute since it falls back to the (HTML-safe) label.+ assert_no_selector ".translation_missing"+ assert_text "Projected"+ assert_text projected.format+ end++ test "falls back to zero when neither a Balance row nor a projection exists" do+ account = accounts(:depository)++ data = Account::ActivityFeedData::ActivityDateData.new(+ date: Date.current,+ entries: [],+ balance: nil,+ projected_balance_money: nil,+ transfers: [],+ split_parents: {}+ )++ component = UI::Account::ActivityDate.new(account: account, data: data)++ assert_equal Money.new(0, account.currency), component.end_balance_money+ refute component.projected?++ render_inline(component)++ assert_no_selector ".translation_missing"+ assert_text "No balance data available for this date"+ end++ test "uses the date's own Balance row when one exists, even if a projection was computed" do+ account = accounts(:depository)+ balance = balances(:one)++ data = Account::ActivityFeedData::ActivityDateData.new(+ date: balance.date,+ entries: [],+ balance: balance,+ projected_balance_money: nil,+ transfers: [],+ split_parents: {}+ )++ component = UI::Account::ActivityDate.new(account: account, data: data)++ assert_equal balance.end_balance_money, component.end_balance_money+ refute component.projected?++ render_inline(component)++ assert_no_selector ".translation_missing"+ end+enddiff --git a/test/controllers/accounts_controller_test.rb b/test/controllers/accounts_controller_test.rbindex 207531d26a..bbdb454e9e 100644--- a/test/controllers/accounts_controller_test.rb+++ b/test/controllers/accounts_controller_test.rb@@ -492,6 +492,32 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestassert_response :successend+ test "show renders the scheduled balance tooltip when a scheduled transaction exists" do+ create_transaction(account: @account, amount: 200, date: 3.days.from_now.to_date)++ get account_url(@account)++ assert_response :success+ assert_select "[data-controller='DS--tooltip']"+ end++ test "show adds the scheduled projection to the investment value tooltip" do+ investment_account = accounts(:investment)+ create_transaction(account: investment_account, amount: 200, date: 3.days.from_now.to_date)++ get account_url(investment_account)++ assert_response :success+ assert_select "[role='tooltip']", text: /#{I18n.t("investments.value_tooltip.projected")}/+ end++ test "show omits the scheduled projection from the investment value tooltip without scheduled entries" do+ get account_url(accounts(:investment))++ assert_response :success+ assert_select "[role='tooltip']", text: /#{I18n.t("investments.value_tooltip.projected")}/, count: 0+ end+test "show renders the balance chart as drag-selectable for a custom date range" doget account_url(@account)diff --git a/test/controllers/transactions_controller_test.rb b/test/controllers/transactions_controller_test.rbindex f4b1cba03f..31b3664979 100644--- a/test/controllers/transactions_controller_test.rb+++ b/test/controllers/transactions_controller_test.rb@@ -700,6 +700,24 @@ class TransactionsControllerTest < ActionDispatch::IntegrationTest# Only finds 1 transaction that matches filterassert_dom "#" + dom_id(searchable_transaction), count: 1assert_dom "#total-transactions", count: 1, text: "1"+ assert_dom "#scheduled-transactions-count", count: 0+ end++ test "transaction count includes scheduled entries shown in the list" do+ family = families(:empty)+ sign_in users(:empty)+ account = family.accounts.create! name: "Test", balance: 0, currency: "USD", accountable: Depository.new++ create_transaction(account: account)+ scheduled = create_transaction(account: account, date: 1.day.from_now.to_date, name: "Scheduled bill")++ get transactions_url++ # The scheduled entry is excluded from totals.count (see Transaction::Search#totals)+ # but still rendered in the list below -- the headline must match the list, not the totals.+ assert_dom "#" + dom_id(scheduled), count: 1+ assert_dom "#total-transactions", count: 1, text: "2"+ assert_dom "#scheduled-transactions-count", count: 1, text: "including 1 scheduled"endtest "can update notes on split child transaction" do@@ -1042,6 +1060,7 @@ endsearch = Transaction::Search.new(family)totals = OpenStruct.new(count: 1,+ excluded_scheduled_count: 0,expense_money: Money.new(10000, "USD"),income_money: Money.new(0, "USD"),transfer_inflow_money: Money.new(0, "USD"),@@ -1066,6 +1085,7 @@ endsearch = Transaction::Search.new(family, filters: { "categories" => [ "Food" ], "types" => [ "expense" ] })totals = OpenStruct.new(count: 1,+ excluded_scheduled_count: 0,expense_money: Money.new(10000, "USD"),income_money: Money.new(0, "USD"),transfer_inflow_money: Money.new(0, "USD"),@@ -1089,6 +1109,7 @@ endsearch = Transaction::Search.new(family, filters: { "types" => [ "transfer" ] })totals = OpenStruct.new(count: 2,+ excluded_scheduled_count: 0,expense_money: Money.new(0, "USD"),income_money: Money.new(0, "USD"),transfer_inflow_money: Money.new(5000, "USD"),diff --git a/test/jobs/entry_scheduled_sync_job_test.rb b/test/jobs/entry_scheduled_sync_job_test.rbnew file mode 100644index 0000000000..a3c69bfb24--- /dev/null+++ b/test/jobs/entry_scheduled_sync_job_test.rb@@ -0,0 +1,58 @@+require "test_helper"++class EntryScheduledSyncJobTest < ActiveJob::TestCase+ include EntriesTestHelper++ test "schedule_for enqueues a job for the entry's date when scheduled" do+ entry = create_transaction(account: accounts(:depository), date: 3.days.from_now.to_date)++ assert_enqueued_with(job: EntryScheduledSyncJob, args: [ entry.id ]) do+ EntryScheduledSyncJob.schedule_for(entry)+ end+ end++ test "schedule_for runs just after midnight in the family's timezone" do+ families(:dylan_family).update!(timezone: "America/New_York")+ entry = create_transaction(account: accounts(:depository), date: 3.days.from_now.to_date)+ expected_run_at = entry.date.in_time_zone("America/New_York") + 5.minutes++ assert_enqueued_with(job: EntryScheduledSyncJob, at: expected_run_at) do+ EntryScheduledSyncJob.schedule_for(entry)+ end+ end++ test "schedule_for does nothing for a non-scheduled entry" do+ entry = create_transaction(account: accounts(:depository), date: Date.current)++ assert_no_enqueued_jobs do+ EntryScheduledSyncJob.schedule_for(entry)+ end+ end++ test "schedule_for_entries enqueues one job per account and date, skipping non-scheduled entries" do+ account = accounts(:depository)+ date = 3.days.from_now.to_date+ first = create_transaction(account: account, date: date)+ second = create_transaction(account: account, date: date)+ later = create_transaction(account: account, date: date + 1.day)+ today = create_transaction(account: account, date: Date.current)++ assert_enqueued_jobs 2, only: EntryScheduledSyncJob do+ EntryScheduledSyncJob.schedule_for_entries(Entry.where(id: [ first.id, second.id, later.id, today.id ]))+ end+ end++ test "perform triggers a sync for the entry's account" do+ entry = create_transaction(account: accounts(:depository), date: 3.days.from_now.to_date)++ Account.any_instance.expects(:sync_later).once++ EntryScheduledSyncJob.perform_now(entry.id)+ end++ test "perform is a no-op when the entry no longer exists" do+ assert_nothing_raised do+ EntryScheduledSyncJob.perform_now("nonexistent-id")+ end+ end+enddiff --git a/test/models/account/activity_feed_data_test.rb b/test/models/account/activity_feed_data_test.rbindex ec093791bd..e5f6d810a0 100644--- a/test/models/account/activity_feed_data_test.rb+++ b/test/models/account/activity_feed_data_test.rb@@ -49,6 +49,22 @@ class Account::ActivityFeedDataTest < ActiveSupport::TestCaseassert_not_nil day1_activityassert_nil day1_activity.balance+ assert_nil day1_activity.projected_balance_money+ end++ test "projects a balance for a scheduled (future-dated) entry with no Balance row" do+ scheduled_date = Date.current + 5.days+ create_transaction(account: @checking, date: scheduled_date, amount: 150, name: "Scheduled bill")++ entries = @checking.entries.includes(:entryable).to_a+ feed_data = Account::ActivityFeedData.new(@checking, entries)++ activities = feed_data.entries_by_date+ scheduled_activity = find_activity_for_date(activities, scheduled_date)++ assert_not_nil scheduled_activity+ assert_nil scheduled_activity.balance+ assert_equal @checking.balance_money - Money.new(150, "USD"), scheduled_activity.projected_balance_moneyendtest "returns cash and holdings data for investment accounts" dodiff --git a/test/models/account/provider_import_adapter_test.rb b/test/models/account/provider_import_adapter_test.rbindex ad620ac3fa..70ff72f748 100644--- a/test/models/account/provider_import_adapter_test.rb+++ b/test/models/account/provider_import_adapter_test.rb@@ -1443,6 +1443,78 @@ class Account::ProviderImportAdapterTest < ActiveSupport::TestCaseendend+ test "claims a transaction entered ahead of time when the provider books it a few days off" do+ expected_date = 2.days.ago.to_date+ scheduled_entry = travel_to(10.days.ago) { create_user_entered_transaction(date: expected_date, amount: 200, name: "Gas bill") }++ assert_no_difference "@account.entries.count" do+ entry = @adapter.import_transaction(+ external_id: "enable_banking_gas",+ amount: 200,+ currency: "USD",+ date: Date.current,+ name: "PRLV GAZ",+ source: "enable_banking"+ )++ assert_equal scheduled_entry.id, entry.id+ assert_equal "enable_banking_gas", entry.external_id+ assert_equal Date.current, entry.date, "moves to the day the provider booked it"+ assert_equal "Gas bill", entry.name, "keeps the user's own name"+ end+ end++ test "does not claim a transaction entered ahead of time outside the matching window" do+ expected_date = 10.days.ago.to_date+ scheduled_entry = travel_to(20.days.ago) { create_user_entered_transaction(date: expected_date, amount: 200, name: "Gas bill") }++ assert_difference "@account.entries.count", 1 do+ entry = @adapter.import_transaction(+ external_id: "enable_banking_gas_late",+ amount: 200,+ currency: "USD",+ date: Date.current,+ name: "PRLV GAZ",+ source: "enable_banking"+ )++ assert_not_equal scheduled_entry.id, entry.id+ end+ end++ test "a pending claim of a transaction entered ahead of time reconciles with its booked version" do+ expected_date = Date.current+ scheduled_entry = travel_to(10.days.ago) { create_user_entered_transaction(date: expected_date, amount: 200, name: "Gas bill") }++ pending_entry = @adapter.import_transaction(+ external_id: "simplefin_gas_pending",+ amount: 200,+ currency: "USD",+ date: expected_date - 1.day,+ name: "PRLV GAZ",+ source: "simplefin",+ extra: { "simplefin" => { "pending" => true } }+ )++ assert_equal scheduled_entry.id, pending_entry.id+ assert pending_entry.transaction.pending?++ assert_no_difference "@account.entries.count" do+ posted_entry = @adapter.import_transaction(+ external_id: "simplefin_gas_posted",+ amount: 200,+ currency: "USD",+ date: expected_date,+ name: "PRLV GAZ",+ source: "simplefin",+ extra: { "simplefin" => { "pending" => false } }+ )++ assert_equal scheduled_entry.id, posted_entry.id+ assert_not posted_entry.transaction.pending?+ end+ end+# ============================================================================# Pending→Posted Transaction Reconciliation Tests# ============================================================================@@ -2516,4 +2588,13 @@ class Account::ProviderImportAdapterTest < ActiveSupport::TestCaseaccount_provider_id: account_provider.id)end++ # Locked and user-modified, the way TransactionsController#create leaves a+ # transaction the user typed in.+ def create_user_entered_transaction(date:, amount:, name:)+ entry = @account.entries.create!(date: date, amount: amount, currency: "USD", name: name, entryable: Transaction.new)+ entry.lock_saved_attributes!+ entry.mark_user_modified!+ entry+ endenddiff --git a/test/models/account_test.rb b/test/models/account_test.rbindex f1dd8b07d6..9529f6de99 100644--- a/test/models/account_test.rb+++ b/test/models/account_test.rb@@ -989,6 +989,121 @@ class AccountTest < ActiveSupport::TestCaseassert transfers.all? { |transfer| !Transfer.exists?(transfer.id) }end+ test "projected_balance_money nets scheduled entries against an asset account's balance" do+ create_transaction(account: @account, amount: 200, date: 3.days.from_now.to_date) # expense, decreases balance+ create_transaction(account: @account, amount: -50, date: 5.days.from_now.to_date) # income, increases balance++ assert_equal Money.new(-150, "USD"), @account.scheduled_entries_total_money+ assert_equal Money.new(4850, "USD"), @account.projected_balance_money+ end++ test "projected_balance_money keeps the sign for a liability account (expense increases debt)" do+ credit_card = accounts(:credit_card)+ create_transaction(account: credit_card, amount: 200, date: 3.days.from_now.to_date) # expense, increases debt++ assert_equal Money.new(200, "USD"), credit_card.scheduled_entries_total_money+ assert_equal Money.new(1200, "USD"), credit_card.projected_balance_money+ end++ test "projected_balance_money ignores transactions on non-cash valuation-only accounts" do+ property = accounts(:property)+ create_transaction(account: property, amount: 5000, date: 3.days.from_now.to_date)++ assert_equal Money.new(0, "USD"), property.scheduled_entries_total_money+ assert_equal property.balance_money, property.projected_balance_money+ end++ test "scheduled_entries_total_money ignores future-dated valuations and buy/sell trades" do+ create_valuation(account: @account, amount: 999_999, date: 3.days.from_now.to_date)++ investment = accounts(:investment)+ create_trade(securities(:aapl), account: investment, qty: 1, price: 100, date: 3.days.from_now.to_date)++ assert_equal Money.new(0, "USD"), @account.scheduled_entries_total_money+ assert_equal Money.new(0, "USD"), investment.scheduled_entries_total_money+ end++ test "scheduled_entries_total_money includes future-dated interest/dividend trades" do+ investment = accounts(:investment)++ Entry.create!(+ account: investment,+ name: "Interest",+ date: 3.days.from_now.to_date,+ currency: "USD",+ amount: -50,+ entryable: Trade.new(qty: 0, price: 0, currency: "USD", security: securities(:aapl), investment_activity_label: "Interest")+ )++ assert_equal Money.new(50, "USD"), investment.scheduled_entries_total_money+ assert_equal investment.balance_money + Money.new(50, "USD"), investment.projected_balance_money+ end++ test "projected_balance_money equals balance_money when nothing is scheduled" do+ assert_equal Money.new(0, "USD"), @account.scheduled_entries_total_money+ assert_equal @account.balance_money, @account.projected_balance_money+ end++ test "scheduled_entries_total_money uses custom exchange_rate when present" do+ eur_account = @family.accounts.create!(+ name: "EUR Checking",+ balance: 1000,+ currency: "EUR",+ accountable: Depository.new+ )++ transaction = Transaction.new+ transaction.exchange_rate = 1.10++ Entry.create!(+ account: eur_account,+ name: "Scheduled FX expense",+ date: 3.days.from_now.to_date,+ currency: "USD",+ amount: 100,+ entryable: transaction+ )++ # 100 USD × custom_rate 1.10 = 110 EUR, negated because asset+ assert_equal Money.new(-110, "EUR"), eur_account.scheduled_entries_total_money+ end++ test "scheduled_entries_total_money drops entries with no available exchange rate instead of using the raw amount" do+ create_transaction(account: @account, amount: 200, date: 3.days.from_now.to_date, currency: "USD")+ create_transaction(account: @account, amount: 100, date: 3.days.from_now.to_date, currency: "EUR")++ # The EUR entry has no exchange rate to USD in this test and none can be+ # fetched -- it must be dropped, not added in as a raw 100, to match how+ # Balance::SyncCache drops it once the date arrives (see #1143).+ assert_equal Money.new(-200, "USD"), @account.scheduled_entries_total_money+ end++ test "scheduled_entries_total_money(through_date:) only sums entries on or before that date" do+ create_transaction(account: @account, amount: 200, date: 3.days.from_now.to_date)+ create_transaction(account: @account, amount: 50, date: 10.days.from_now.to_date)++ assert_equal Money.new(-200, "USD"), @account.scheduled_entries_total_money(through_date: 5.days.from_now.to_date)+ assert_equal Money.new(-250, "USD"), @account.scheduled_entries_total_money(through_date: 10.days.from_now.to_date)+ end++ test "scheduled entries are loaded once per instance and reloaded on reload" do+ create_transaction(account: @account, amount: 200, date: 3.days.from_now.to_date)+ create_transaction(account: @account, amount: 50, date: 10.days.from_now.to_date)++ queries = 0+ counter = ->(*, payload) { queries += 1 if payload[:sql].include?("entries.date >") }+ ActiveSupport::Notifications.subscribed(counter, "sql.active_record") do+ @account.scheduled_entries_total_money+ @account.projected_balance_money+ @account.scheduled_entries_total_money(through_date: 3.days.from_now.to_date)+ @account.scheduled_entries_total_money(through_date: 10.days.from_now.to_date)+ end+ assert_equal 1, queries++ create_transaction(account: @account, amount: 25, date: 5.days.from_now.to_date)+ assert_equal Money.new(-275, "USD"), @account.reload.scheduled_entries_total_money+ end+test "history_start_date resolves to the earliest of opening anchor, entries, and balances" doaccount = @family.accounts.create!(owner: @admin,diff --git a/test/models/balance/forward_calculator_test.rb b/test/models/balance/forward_calculator_test.rbindex 11ae65fe51..430fb7715a 100644--- a/test/models/balance/forward_calculator_test.rb+++ b/test/models/balance/forward_calculator_test.rb@@ -86,6 +86,37 @@ class Balance::ForwardCalculatorTest < ActiveSupport::TestCaseassert_not_includes calculated.map(&:date), 1.day.ago.to_dateend+ test "scheduled (future-dated) transactions do not affect materialized balances" do+ account = create_account_with_ledger(+ account: { type: Depository, currency: "USD" },+ entries: [+ { type: "opening_anchor", date: 3.days.ago.to_date, balance: 1000 },+ { type: "transaction", date: 2.days.ago.to_date, amount: -200 },+ { type: "transaction", date: 1.day.from_now.to_date, amount: -5000 }+ ]+ )++ calculated = Balance::ForwardCalculator.new(account).calculate++ assert_equal 1200, calculated.last.balance+ assert_equal 2.days.ago.to_date, calculated.map(&:date).max+ assert_not_includes calculated.map(&:date), 1.day.from_now.to_date+ end++ test "account whose only entry is scheduled more than a day out still gets a Date.current balance" do+ account = create_account_with_ledger(+ account: { type: Depository, currency: "USD" },+ entries: [+ { type: "transaction", date: 3.days.from_now.to_date, amount: -1000 }+ ]+ )++ calculated = Balance::ForwardCalculator.new(account).calculate++ assert_equal [ Date.current ], calculated.map(&:date)+ assert_equal 0, calculated.first.balance+ end+test "calculation start date ignores a pending entry before the opening anchor" doaccount = create_account_with_ledger(account: { type: Depository, currency: "USD" },diff --git a/test/models/balance/materializer_test.rb b/test/models/balance/materializer_test.rbindex 3ab4309809..72ba99d545 100644--- a/test/models/balance/materializer_test.rb+++ b/test/models/balance/materializer_test.rb@@ -86,6 +86,19 @@ class Balance::MaterializerTest < ActiveSupport::TestCase"Recalculated balance for 2.days.ago should be persisted"end+ # Regression: account.balance must never surface a future-dated balance row,+ # even if one exists in the table (e.g. left behind by a race between+ # overlapping syncs). purge_stale_balances is the primary defense, but+ # update_account_info must not rely on it exclusively -- see Entry#scheduled?.+ test "update_account_info ignores future-dated balance rows even if one exists" do+ create_balance(account: @account, date: Date.current, balance: 20000)+ create_balance(account: @account, date: 3.days.from_now.to_date, balance: 99000)++ Balance::Materializer.new(@account, strategy: :forward).send(:update_account_info)++ assert_equal 20000, @account.reload.balance+ end+# Regression: a prior full sync materializes balances for entries dated BEFORE# the opening anchor; a later incremental sync (window after the anchor) must# preserve them. The purge lower bound uses calculation_start_date — the samediff --git a/test/models/budget_test.rb b/test/models/budget_test.rbindex 11cad89ec8..d1c9fe39bb 100644--- a/test/models/budget_test.rb+++ b/test/models/budget_test.rb@@ -376,6 +376,41 @@ class BudgetTest < ActiveSupport::TestCaseassert_equal 150, spending_without_refund - spending_with_refundend+ test "actual_spending excludes scheduled (future-dated) entries" do+ travel_to Date.current.beginning_of_month do+ family = families(:dylan_family)+ budget = Budget.find_or_bootstrap(family, start_date: Date.current.beginning_of_month)+ account = accounts(:depository)++ healthcare = Category.create!(+ name: "Healthcare #{Time.now.to_f}",+ family: family,+ color: "#e74c3c"+ )++ budget.sync_budget_categories+ budget_category = budget.budget_categories.find_by(category: healthcare)+ budget_category.update!(budgeted_spending: 200)++ # A bill scheduled for later this month -- hasn't happened yet+ Entry.create!(+ account: account,+ entryable: Transaction.create!(category: healthcare),+ date: Date.current + 10.days,+ name: "Scheduled dentist bill",+ amount: 150,+ currency: "USD"+ )++ budget = Budget.find(budget.id)+ budget.sync_budget_categories++ assert_equal 0, budget.budget_category_actual_spending(+ budget.budget_categories.find_by(category: healthcare)+ )+ end+ end+test "most_recent_initialized_budget returns latest initialized budget before this one" dofamily = families(:dylan_family)diff --git a/test/models/entry_test.rb b/test/models/entry_test.rbindex 761920e96f..88e4dcdcb8 100644--- a/test/models/entry_test.rb+++ b/test/models/entry_test.rb@@ -1,7 +1,7 @@require "test_helper"class EntryTest < ActiveSupport::TestCase- include EntriesTestHelper+ include EntriesTestHelper, ActiveJob::TestHelpertest "chronological ordering uses id as final tie breaker" doaccount = accounts(:depository)@@ -58,6 +58,42 @@ class EntryTest < ActiveSupport::TestCaseassert_not_nil category.reload.last_used_atend+ test "bulk_update! syncs each account once and schedules the catch-up job when dates move into the future" do+ account = accounts(:depository)+ entries = [ create_transaction(account: account), create_transaction(account: account) ]+ new_date = 3.days.from_now.to_date++ Account.any_instance.expects(:sync_later).with(window_start_date: Date.current).once++ assert_enqueued_jobs 1, only: EntryScheduledSyncJob do+ Entry.where(id: entries.map(&:id)).bulk_update!({ date: new_date })+ end+ end++ test "bulk_update! neither syncs nor schedules when no date changes" do+ entry = create_transaction(account: accounts(:depository))++ Account.any_instance.expects(:sync_later).never++ assert_no_enqueued_jobs only: EntryScheduledSyncJob do+ Entry.where(id: entry.id).bulk_update!({ notes: "updated" })+ end+ end++ test "scheduled? is true only for entries dated after today" do+ travel_to Date.new(2026, 5, 5) do+ account = accounts(:depository)++ future_entry = create_transaction(account: account, date: 1.day.from_now.to_date)+ today_entry = create_transaction(account: account, date: Date.current)+ past_entry = create_transaction(account: account, date: 1.day.ago.to_date)++ assert future_entry.scheduled?+ assert_not today_entry.scheduled?+ assert_not past_entry.scheduled?+ end+ end+test "blank name is invalid when auto-generate transaction names is off" dofamilies(:dylan_family).update!(auto_generate_transaction_names: false)diff --git a/test/models/family_test.rb b/test/models/family_test.rbindex 1133549ec1..f255d9cedd 100644--- a/test/models/family_test.rb+++ b/test/models/family_test.rb@@ -620,6 +620,39 @@ class FamilyTest < ActiveSupport::TestCaseassert family.saveend+ test "resolved_time_zone returns the family's zone" do+ family = families(:dylan_family)+ family.update_column(:timezone, "America/New_York")++ assert_equal "America/New_York", family.resolved_time_zone.name+ end++ test "resolved_time_zone falls back to the app default and logs once for a stale/invalid zone" do+ family = families(:dylan_family)+ family.update_column(:timezone, "Invalid/Timezone")++ original_cache = Rails.cache+ Rails.cache = ActiveSupport::Cache::MemoryStore.new++ assert_difference "DebugLogEntry.count", 1 do+ 2.times { assert_equal Time.zone, family.resolved_time_zone }+ end++ entry = DebugLogEntry.order(:created_at).last+ assert_equal "warn", entry.level+ assert_includes entry.message, "Invalid/Timezone"+ assert_equal family, entry.family+ ensure+ Rails.cache = original_cache+ end++ test "resolved_time_zone falls back to the app default for a blank timezone" do+ family = families(:dylan_family)+ family.update_column(:timezone, nil)++ assert_equal Time.zone, family.resolved_time_zone+ end+test "balance_sheet memoizes per user for the same family instance" dofamily = families(:dylan_family)admin = users(:family_admin)diff --git a/test/models/import_test.rb b/test/models/import_test.rbindex 3022467d85..89a9d898f5 100644--- a/test/models/import_test.rb+++ b/test/models/import_test.rb@@ -1,6 +1,8 @@require "test_helper"class ImportTest < ActiveSupport::TestCase+ include ActiveJob::TestHelper+test "publish skips imports in terminal statuses" doimport = imports(:transaction)import.update_columns(status: "complete")@@ -12,6 +14,23 @@ class ImportTest < ActiveSupport::TestCaseassert_equal "complete", import.reload.statusend+ test "publish schedules the catch-up sync for scheduled entries it created" do+ import = imports(:transaction)+ account = accounts(:depository)+ import.define_singleton_method(:import!) do+ account.entries.create!(+ name: "Upcoming bill", date: 3.days.from_now.to_date, amount: 100, currency: "USD",+ entryable: Transaction.new, import: self+ )+ end++ assert_enqueued_jobs 1, only: EntryScheduledSyncJob do+ import.publish+ end++ assert_equal "complete", import.reload.status+ end+test "publish skips imports that are reverting" doimport = imports(:transaction)import.update_columns(status: "reverting")diff --git a/test/models/income_statement/spending_comparison_test.rb b/test/models/income_statement/spending_comparison_test.rbindex 204383aa41..ea15cf0d73 100644--- a/test/models/income_statement/spending_comparison_test.rb+++ b/test/models/income_statement/spending_comparison_test.rb@@ -91,9 +91,14 @@ class IncomeStatement::SpendingComparisonTest < ActiveSupport::TestCase(Date.new(2025, 10, 1)...quarter.start_date).each { |d| create_transaction(account: @account, date: d, amount: 10, category: @travel) }(quarter.start_date..Date.new(2026, 12, 20)).each { |d| create_transaction(account: @account, date: d, amount: 30, category: @travel) }- result = IncomeStatement::SpendingComparison.new(IncomeStatement.new(@family), period: quarter, history_start: Date.new(2025, 10, 1), as_of: Date.new(2026, 12, 20))+ # Entry.excluding_scheduled keys off the real Date.current, so "as_of" in+ # the future must be the frozen "today" too, or later entries in the+ # quarter get treated as not-yet-arrived and dropped from the total.+ travel_to(Date.new(2026, 12, 20)) do+ result = IncomeStatement::SpendingComparison.new(IncomeStatement.new(@family), period: quarter, history_start: Date.new(2025, 10, 1), as_of: Date.new(2026, 12, 20))- assert_in_delta 2, result.rows.find { |r| r.category == @travel }.ratio, 0.01+ assert_in_delta 2, result.rows.find { |r| r.category == @travel }.ratio, 0.01+ endendtest "a bill paid on the 1st reads as normal early in the month" dodiff --git a/test/models/income_statement_test.rb b/test/models/income_statement_test.rbindex 40f12848d5..44cb2f4cca 100644--- a/test/models/income_statement_test.rb+++ b/test/models/income_statement_test.rb@@ -139,6 +139,26 @@ class IncomeStatementTest < ActiveSupport::TestCaseendend+ test "a new day invalidates cached daily series, family stats and category stats" do+ period = Period.last_30_days++ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)+ IncomeStatement::DailyExpenseTotals.expects(:new).twice.returns(stub(call: []))+ IncomeStatement::FamilyStats.expects(:new).twice.returns(stub(call: []))+ IncomeStatement::CategoryStats.expects(:new).twice.returns(stub(call: []))++ # Scheduled entries are excluded as of "today", so a result cached+ # yesterday must not be served once one of them has arrived.+ [ Date.current, Date.current + 1.day ].each do |day|+ travel_to day do+ statement = IncomeStatement.new(@family)+ statement.daily_expense_series(period: period)+ statement.median_income+ statement.median_expense(category: @food_category)+ end+ end+ end+test "daily series narrows to categories, a parent covering its subcategories" doperiod = Period.last_30_daysrent = @family.categories.create! name: "Rent"@@ -301,6 +321,25 @@ class IncomeStatementTest < ActiveSupport::TestCaseassert_equal 1500.0, income_statement.median_expense(interval: "month")end+ test "median/avg expense ignore scheduled (future-dated) entries" do+ Entry.joins(:account).where(accounts: { family_id: @family.id }).destroy_all++ create_transaction(account: @checking_account, amount: 100, category: @groceries_category)+ create_transaction(account: @checking_account, amount: 300, category: @groceries_category)++ income_statement = IncomeStatement.new(@family)+ baseline_median = income_statement.median_expense(interval: "month")+ baseline_avg = income_statement.avg_expense(interval: "month")++ # A scheduled bill dated next month would otherwise open a new,+ # partial-month bucket that skews both stats (see #3262 review).+ create_transaction(account: @checking_account, amount: 999_999, category: @groceries_category, date: 1.month.from_now.to_date)++ income_statement_with_scheduled = IncomeStatement.new(@family)+ assert_equal baseline_median, income_statement_with_scheduled.median_expense(interval: "month")+ assert_equal baseline_avg, income_statement_with_scheduled.avg_expense(interval: "month")+ end+test "calculates median income correctly with known dataset" do# Clear existing transactions by deleting entriesEntry.joins(:account).where(accounts: { family_id: @family.id }).destroy_alldiff --git a/test/models/sync_test.rb b/test/models/sync_test.rbindex 747f46ff23..9b9b892d2a 100644--- a/test/models/sync_test.rb+++ b/test/models/sync_test.rb@@ -28,6 +28,52 @@ class SyncTest < ActiveSupport::TestCaseassert_equal "completed", sync.statusend+ test "runs the sync in the family's timezone instead of the app default" do+ account = accounts(:depository)+ account.family.update_column(:timezone, "Pacific/Auckland")+ sync = Sync.create!(syncable: account)++ observed_zone_name = nil+ account.define_singleton_method(:perform_sync) { |_sync| observed_zone_name = Time.zone.name }++ sync.perform++ assert_equal "Pacific/Auckland", observed_zone_name+ end++ test "Date.current inside perform reflects the family's local date, not UTC" do+ account = accounts(:depository)+ account.family.update_column(:timezone, "Pacific/Auckland")+ sync = Sync.create!(syncable: account)++ # 2026-01-14 23:00 UTC is already 2026-01-15 in Auckland (UTC+13 in+ # January, southern-hemisphere DST) -- the exact mismatch from the+ # review: a background job defaults to the app's zone (UTC), so a+ # scheduled entry dated the 15th would still read as "not arrived" there+ # even though it already has for the family.+ observed_date = nil+ account.define_singleton_method(:perform_sync) { |_sync| observed_date = Date.current }++ travel_to Time.utc(2026, 1, 14, 23, 0, 0) do+ sync.perform+ end++ assert_equal Date.new(2026, 1, 15), observed_date+ end++ test "falls back to the app's default timezone when the family's is missing" do+ account = accounts(:depository)+ account.family.update_column(:timezone, nil)+ sync = Sync.create!(syncable: account)++ observed_zone_name = nil+ account.define_singleton_method(:perform_sync) { |_sync| observed_zone_name = Time.zone.name }++ sync.perform++ assert_equal Time.zone.name, observed_zone_name+ end+test "handles sync errors" dosyncable = accounts(:depository)sync = Sync.create!(syncable: syncable)diff --git a/test/models/transaction/search_test.rb b/test/models/transaction/search_test.rbindex a0f8220404..a2406b7328 100644--- a/test/models/transaction/search_test.rb+++ b/test/models/transaction/search_test.rb@@ -382,6 +382,42 @@ class Transaction::SearchTest < ActiveSupport::TestCaseassert_equal Money.new(200, "USD"), totals.income_money # $200end+ test "totals excludes scheduled (future-dated) transactions by default" do+ create_transaction(account: @checking_account, amount: 100, kind: "standard", date: Date.current)+ create_transaction(account: @checking_account, amount: 5000, kind: "standard", date: 3.days.from_now.to_date)++ search = Transaction::Search.new(@family)+ totals = search.totals++ assert_equal 1, totals.count+ assert_equal 1, totals.excluded_scheduled_count+ assert_equal Money.new(100, "USD"), totals.expense_money+ end++ test "totals includes scheduled transactions when an explicit end_date filter is set" do+ create_transaction(account: @checking_account, amount: 100, kind: "standard", date: Date.current)+ create_transaction(account: @checking_account, amount: 5000, kind: "standard", date: 3.days.from_now.to_date)++ search = Transaction::Search.new(@family, filters: { end_date: 10.days.from_now.to_date.to_s })+ totals = search.totals++ assert_equal 2, totals.count+ assert_equal 0, totals.excluded_scheduled_count+ assert_equal Money.new(5100, "USD"), totals.expense_money+ end++ test "totals includes scheduled transactions when start_date is after today" do+ create_transaction(account: @checking_account, amount: 100, kind: "standard", date: Date.current)+ create_transaction(account: @checking_account, amount: 200, kind: "standard", date: 10.days.from_now.to_date)++ search = Transaction::Search.new(@family, filters: { start_date: 1.day.from_now.to_date.to_s })+ totals = search.totals++ assert_equal 1, totals.count+ assert_equal 0, totals.excluded_scheduled_count+ assert_equal Money.new(200, "USD"), totals.expense_money+ end+test "totals handles multi-currency transactions with exchange rates" do# Create EUR transactioneur_entry = create_transaction(@@ -494,7 +530,7 @@ class Transaction::SearchTest < ActiveSupport::TestCasekey2 = search2.cache_key_baseassert_equal key1, key2- assert_not_nil cache.read("transaction_search_totals/v3/#{key2}")+ assert_not_nil cache.read("transaction_search_totals/v4/#{key2}")assert_equal result1, search2.totalsenddiff --git a/test/models/transfer/creator_test.rb b/test/models/transfer/creator_test.rbindex 6e10e1288d..493d95b043 100644--- a/test/models/transfer/creator_test.rb+++ b/test/models/transfer/creator_test.rb@@ -1,6 +1,8 @@require "test_helper"class Transfer::CreatorTest < ActiveSupport::TestCase+ include ActiveJob::TestHelper+setup do@family = families(:dylan_family)@source_account = accounts(:depository)@@ -319,6 +321,39 @@ class Transfer::CreatorTest < ActiveSupport::TestCaseassert_in_delta(-0.0001, transfer.inflow_transaction.entry.amount, 0.0001)end+ test "schedules entry scheduled sync jobs for future-dated transfers" do+ creator = Transfer::Creator.new(+ family: @family,+ source_account_id: @source_account.id,+ destination_account_id: @destination_account.id,+ date: 3.days.from_now.to_date,+ amount: @amount+ )++ transfer = nil+ assert_enqueued_jobs 2, only: EntryScheduledSyncJob do+ transfer = creator.create+ end++ enqueued_ids = enqueued_jobs.select { |j| j["job_class"] == "EntryScheduledSyncJob" }.flat_map { |j| j["arguments"] }+ assert_includes enqueued_ids, transfer.inflow_transaction.entry.id+ assert_includes enqueued_ids, transfer.outflow_transaction.entry.id+ end++ test "syncs both accounts for a same-day (non-scheduled) transfer" do+ creator = Transfer::Creator.new(+ family: @family,+ source_account_id: @source_account.id,+ destination_account_id: @destination_account.id,+ date: Date.current,+ amount: @amount+ )++ Account.any_instance.expects(:sync_later).at_least(2)++ creator.create+ end+test "creates transfer with tags applied to both transactions" doother_depository = @family.accounts.create!(name: "Savings", balance: 1000, currency: "USD", accountable: Depository.new)tag = tags(:one)