The personal finance app for everyone (by everyone)
Ruby
fix: allow recurring transfers with the same accounts and amount on different days (#4855)
Chris Werner Rau48da27eafdc3
diff --git a/app/controllers/transfers_controller.rb b/app/controllers/transfers_controller.rbindex 41bf70ef12..d5901ab9d0 100644--- a/app/controllers/transfers_controller.rb+++ b/app/controllers/transfers_controller.rb@@ -166,14 +166,7 @@ class TransfersController < ApplicationControllerreturn unless require_account_permission!(source_account)return unless require_account_permission!(destination_account)- existing = Current.family.recurring_transactions.find_by(- account_id: source_account.id,- destination_account_id: destination_account.id,- amount: @transfer.outflow_transaction.entry.amount,- currency: @transfer.outflow_transaction.entry.currency- )-- if existing+ if RecurringTransaction.transfer_series_for(@transfer)flash[:alert] = t("recurring_transactions.transfer_already_exists")respond_to do |format|format.html { redirect_back_or_to transactions_path }@@ -188,9 +181,15 @@ class TransfersController < ApplicationControllerformat.html { redirect_back_or_to transactions_path }endrescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique- # RecordNotUnique covers the race window between `find_by` and `create!`- # (the partial unique index protects us at the DB level).- flash[:alert] = t("recurring_transactions.transfer_creation_failed")+ # RecordNotUnique covers the race window between the series lookup and+ # `create!` (the partial unique index protects us at the DB level). When+ # the colliding series is the one we were creating, a concurrent request+ # won the insert, which is the same outcome as marking it twice.+ flash[:alert] = if RecurringTransaction.transfer_series_for(@transfer)+ t("recurring_transactions.transfer_already_exists")+ else+ t("recurring_transactions.transfer_creation_failed")+ endrespond_to do |format|format.html { redirect_back_or_to transactions_path }enddiff --git a/app/models/recurring_transaction.rb b/app/models/recurring_transaction.rbindex 81aca2df1d..c59ab94a0e 100644--- a/app/models/recurring_transaction.rb+++ b/app/models/recurring_transaction.rb@@ -63,6 +63,8 @@ class RecurringTransaction < ApplicationRecordnormalizes :payment_url, with: ->(url) { normalize_payment_url(url) }before_validation :derive_transfer_bill_type+ validate :transfer_day_not_taken, on: :update, if: :transfer_day_changing?+ before_save :sync_transfer_dedup_scope, if: :transfer_day_changing?# Columns whose change reshapes the occurrence stream. Amount is absent on# purpose: open occurrences inherit it at read time.@@ -373,6 +375,29 @@ class RecurringTransaction < ApplicationRecordself.bill_type = "transfer" if transfer?end+ # create_from_transfer keys a transfer series by its day in dedup_scope (a+ # legacy series has none). Moving the series to another day moves the key+ # with it, or the unique index would keep guarding the old day.+ def transfer_day_changing?+ transfer? && persisted? && will_save_change_to_expected_day_of_month? &&+ (dedup_scope.blank? || dedup_scope.start_with?("day-"))+ end++ def sync_transfer_dedup_scope+ self.dedup_scope = "day-#{expected_day_of_month}"+ end++ # A series cannot move onto the day another series between the same accounts+ # and amount already holds, whatever its dedup_scope.+ def transfer_day_not_taken+ taken = self.class.where(+ family_id: family_id, account_id: account_id, destination_account_id: destination_account_id,+ amount: amount, currency: currency, expected_day_of_month: expected_day_of_month+ ).where.not(id: id).exists?++ errors.add(:expected_day_of_month, :taken) if taken+ end+def bill_type_matches_shapeif typed_transfer? && !transfer?errors.add(:bill_type, :transfer_shape_mismatch)@@ -624,6 +649,47 @@ class RecurringTransaction < ApplicationRecordCleaner.new(family).cleanup_stale_transactionsend+ # The recurring transfer a Transfer already belongs to: same accounts,+ # amount and currency, and the transfer's date falls on the series' schedule,+ # including its posting tolerance (a standing order due on a Saturday posts+ # the following Monday). Where several series cover the date, the closest+ # day wins, an exact day before a clamped one. Payments between the same+ # accounts for the same amount more than the tolerance apart are separate+ # series.+ def self.transfer_series_for(transfer)+ outflow_entry = transfer.outflow_transaction&.entry+ inflow_entry = transfer.inflow_transaction&.entry+ return nil unless outflow_entry && inflow_entry++ date = outflow_entry.date+ candidates = where(+ family_id: outflow_entry.account.family_id,+ account_id: outflow_entry.account_id,+ destination_account_id: inflow_entry.account_id,+ amount: outflow_entry.amount,+ currency: outflow_entry.currency+ ).select { |series| series.schedule.matches_day?(date) }++ candidates.min_by { |series| transfer_day_rank(series, date) }+ end++ # Days between a date and the series' nearest monthly occurrence, looking at+ # the neighbouring months too: a day-31 series' April 30 occurrence is one+ # day from May 1.+ def self.transfer_day_distance(series, date)+ [ -1, 0, 1 ].map do |offset|+ month_start = date.beginning_of_month.advance(months: offset)+ scheduled_day = [ series.expected_day_of_month, month_start.end_of_month.day ].min+ (date - month_start.change(day: scheduled_day)).abs.to_i+ end.min+ end++ # Orders series for a date: nearest occurrence first, then an exact day over+ # a clamped one (day 28 over day 31 on Feb 28), then id for a stable result.+ def self.transfer_day_rank(series, date)+ [ transfer_day_distance(series, date), series.expected_day_of_month == date.day ? 0 : 1, series.id ]+ end+# Create a manual recurring transfer from an existing Transfer pair.# Mirrors `create_from_transaction` but populates source + destination# accounts and skips merchant / variance lookup -- transfers are@@ -651,6 +717,9 @@ class RecurringTransaction < ApplicationRecord# name_prefix logic so the recurring row reads consistently with# the originating Transfer.name: transfer.name,+ # Same accounts and amount on another day of the month is another series;+ # the day in dedup_scope keeps their unique-index keys apart.+ dedup_scope: "day-#{expected_day}",amount: outflow_entry.amount, # positive (outflow), per Sure sign conventioncurrency: outflow_entry.currency,expected_day_of_month: expected_day,diff --git a/app/models/recurring_transaction/cleaner.rb b/app/models/recurring_transaction/cleaner.rbindex dda0538d56..16f74a77af 100644--- a/app/models/recurring_transaction/cleaner.rb+++ b/app/models/recurring_transaction/cleaner.rb@@ -28,6 +28,7 @@ class RecurringTransaction# Double-check if there are any recent matching transactionsthreshold = recurring_transaction.staleness_threshold_daterecent_matches = recurring_transaction.matching_transactions.select { |entry| entry.date >= threshold }+ recent_matches = unclaimed_by_other_series(recurring_transaction, recent_matches) if recurring_transaction.transfer?if recent_matches.empty?recurring_transaction.mark_inactive!@@ -91,5 +92,21 @@ class RecurringTransaction.where(manual: false, destination_account_id: nil).where.not(id: claimed_ids)end++ # Same-amount transfer series between the same accounts sit within each+ # other's posting tolerance, so one transfer can fit several. Once the+ # Matcher has confirmed it as another series' payment it is not evidence+ # that this one is still running.+ def unclaimed_by_other_series(series, entries)+ return entries if entries.empty?++ claimed_entry_ids = RecurringAllocation.confirmed+ .joins(:recurring_occurrence)+ .where(entry_id: entries.map(&:id))+ .where.not(recurring_occurrences: { recurring_transaction_id: series.id })+ .pluck(:entry_id)++ entries.reject { |entry| claimed_entry_ids.include?(entry.id) }+ endendenddiff --git a/test/controllers/transfers_controller_test.rb b/test/controllers/transfers_controller_test.rbindex ba88330c96..8177cb0ee6 100644--- a/test/controllers/transfers_controller_test.rb+++ b/test/controllers/transfers_controller_test.rb@@ -1092,6 +1092,68 @@ class TransfersControllerTest < ActionDispatch::IntegrationTestassert_equal I18n.t("recurring_transactions.transfer_already_exists"), flash[:alert]end+ test "mark_as_recurring accepts two transfers with the same accounts and amount on different days" do+ family = users(:family_admin).family+ family.recurring_transactions.destroy_all+ first = create_dated_transfer(date: Date.new(2026, 1, 1))+ second = create_dated_transfer(date: Date.new(2026, 1, 28))++ assert_difference -> { RecurringTransaction.where(family: family).count }, +2 do+ post mark_as_recurring_transfer_url(first)+ assert_equal I18n.t("recurring_transactions.transfer_marked_as_recurring"), flash[:notice]+ post mark_as_recurring_transfer_url(second)+ assert_equal I18n.t("recurring_transactions.transfer_marked_as_recurring"), flash[:notice]+ end++ assert_equal [ 1, 28 ], RecurringTransaction.where(family: family).order(:expected_day_of_month).pluck(:expected_day_of_month)+ end++ test "mark_as_recurring recognises a transfer posted a weekend later than its series" do+ family = users(:family_admin).family+ family.recurring_transactions.destroy_all+ july = create_dated_transfer(date: Date.new(2026, 7, 1))+ # August 1 is a Saturday: the standing order posts on Monday the 3rd.+ august = create_dated_transfer(date: Date.new(2026, 8, 3))++ post mark_as_recurring_transfer_url(july)++ assert_no_difference -> { RecurringTransaction.where(family: family).count } do+ post mark_as_recurring_transfer_url(august)+ end+ assert_equal I18n.t("recurring_transactions.transfer_already_exists"), flash[:alert]+ end++ test "mark_as_recurring flags a second transfer on the same day of the same series as already existing" do+ family = users(:family_admin).family+ family.recurring_transactions.destroy_all+ january = create_dated_transfer(date: Date.new(2026, 1, 28))+ february = create_dated_transfer(date: Date.new(2026, 2, 28))++ post mark_as_recurring_transfer_url(january)++ assert_no_difference -> { RecurringTransaction.where(family: family).count } do+ post mark_as_recurring_transfer_url(february)+ end+ assert_equal I18n.t("recurring_transactions.transfer_already_exists"), flash[:alert]+ end++ test "mark_as_recurring reports already-exists when a concurrent request wins the insert" do+ family = users(:family_admin).family+ family.recurring_transactions.destroy_all+ transfer = create_dated_transfer(date: Date.new(2026, 1, 28))+ winner = RecurringTransaction.create_from_transfer(transfer)++ # Our lookup misses, the other request's insert has already landed when+ # ours collides with it.+ RecurringTransaction.stubs(:transfer_series_for).returns(nil).then.returns(winner)+ RecurringTransaction.stubs(:create_from_transfer).raises(ActiveRecord::RecordNotUnique)++ assert_no_difference -> { RecurringTransaction.where(family: family).count } do+ post mark_as_recurring_transfer_url(transfer)+ end+ assert_equal I18n.t("recurring_transactions.transfer_already_exists"), flash[:alert]+ end+test "mark_as_recurring is rejected when recurring_transactions_disabled" dotransfer = transfers(:one)family = users(:family_admin).family@@ -1105,6 +1167,13 @@ class TransfersControllerTest < ActionDispatch::IntegrationTestendprivate+ def create_dated_transfer(date:, amount: 2000)+ outflow_entry = create_transaction(date: date, account: accounts(:depository), amount: amount)+ inflow_entry = create_transaction(date: date, account: accounts(:investment), amount: -amount)++ Transfer.create!(inflow_transaction: inflow_entry.transaction, outflow_transaction: outflow_entry.transaction).tap(&:confirm!)+ end+def create_confirmed_transfer(to:)outflow_entry = create_transaction(date: Date.current, account: accounts(:depository), amount: 500)inflow_entry = create_transaction(date: Date.current, account: to, amount: -500)diff --git a/test/models/recurring_transaction_test.rb b/test/models/recurring_transaction_test.rbindex 9a2a3ad1dc..6abf5dfac8 100644--- a/test/models/recurring_transaction_test.rb+++ b/test/models/recurring_transaction_test.rb@@ -1477,6 +1477,169 @@ class RecurringTransactionTest < ActiveSupport::TestCaseassert_equal "active", rt.statusend+ test "create_from_transfer keeps same-amount series between the same accounts apart by day" do+ source = @account+ destination = accounts(:credit_card)++ first = build_transfer_between(source, destination, Date.new(2026, 1, 1))+ second = build_transfer_between(source, destination, Date.new(2026, 1, 28))+ repeat = build_transfer_between(source, destination, Date.new(2026, 2, 28))++ RecurringTransaction.create_from_transfer(first)+ day28 = RecurringTransaction.create_from_transfer(second)++ assert_equal [ 1, 28 ], @family.recurring_transactions.where(destination_account: destination).order(:expected_day_of_month).pluck(:expected_day_of_month)+ assert_equal day28, RecurringTransaction.transfer_series_for(repeat)+ assert_raises(ActiveRecord::RecordNotUnique) { RecurringTransaction.create_from_transfer(repeat) }+ end++ test "transfer_series_for finds a series edited to a non-monthly cadence" do+ source = @account+ destination = accounts(:credit_card)+ series = RecurringTransaction.create_from_transfer(build_transfer_between(source, destination, Date.new(2026, 1, 5)))+ RecurringTransaction::FrequencyPreset.apply(series, preset: "weekly", weekday: Date.new(2026, 1, 5).wday)+ series.save!++ later_week = build_transfer_between(source, destination, Date.new(2026, 1, 19))++ assert_equal series, RecurringTransaction.transfer_series_for(later_week)+ end++ test "editing the day of a recurring transfer keeps its dedup_scope in step" do+ source = @account+ destination = accounts(:credit_card)+ series = RecurringTransaction.create_from_transfer(build_transfer_between(source, destination, Date.new(2026, 1, 1)))++ series.update!(expected_day_of_month: 28)++ assert_equal "day-28", series.reload.dedup_scope+ assert_nothing_raised do+ RecurringTransaction.create_from_transfer(build_transfer_between(source, destination, Date.new(2026, 2, 1)))+ end+ end++ test "editing a recurring transfer onto the day of another series is invalid" do+ source = @account+ destination = accounts(:credit_card)+ RecurringTransaction.create_from_transfer(build_transfer_between(source, destination, Date.new(2026, 1, 28)))+ series = RecurringTransaction.create_from_transfer(build_transfer_between(source, destination, Date.new(2026, 1, 1)))++ assert_not series.update(expected_day_of_month: 28)+ assert series.errors[:expected_day_of_month].present?+ assert_equal 1, series.reload.expected_day_of_month+ assert_equal "day-1", series.dedup_scope+ end++ test "transfer_series_for finds a day-31 series for the last day of a short month" do+ source = @account+ destination = accounts(:credit_card)+ series = RecurringTransaction.create_from_transfer(build_transfer_between(source, destination, Date.new(2026, 1, 31)))++ assert_equal series, RecurringTransaction.transfer_series_for(build_transfer_between(source, destination, Date.new(2026, 2, 28)))+ assert_nil RecurringTransaction.transfer_series_for(build_transfer_between(source, destination, Date.new(2026, 2, 25)))+ end++ test "transfer_series_for keeps a day-28 transfer apart from a day-31 series when a day-28 series exists" do+ source = @account+ destination = accounts(:credit_card)+ RecurringTransaction.create_from_transfer(build_transfer_between(source, destination, Date.new(2026, 1, 31)))+ day28 = RecurringTransaction.create_from_transfer(build_transfer_between(source, destination, Date.new(2026, 1, 28)))++ assert_equal day28, RecurringTransaction.transfer_series_for(build_transfer_between(source, destination, Date.new(2026, 2, 28)))+ end++ test "transfer_series_for finds a series for a transfer posted within the posting tolerance" do+ source = @account+ destination = accounts(:credit_card)+ series = RecurringTransaction.create_from_transfer(build_transfer_between(source, destination, Date.new(2026, 7, 1)))++ # August 1 is a Saturday, so the payment lands on Monday the 3rd.+ assert_equal series, RecurringTransaction.transfer_series_for(build_transfer_between(source, destination, Date.new(2026, 8, 3)))+ assert_nil RecurringTransaction.transfer_series_for(build_transfer_between(source, destination, Date.new(2026, 8, 4)))+ end++ test "transfer_series_for prefers the series whose day the transfer is on" do+ source = @account+ destination = accounts(:credit_card)+ RecurringTransaction.create_from_transfer(build_transfer_between(source, destination, Date.new(2026, 7, 1)))+ day3 = RecurringTransaction.create_from_transfer(build_transfer_between(source, destination, Date.new(2026, 7, 3)))++ assert_equal day3, RecurringTransaction.transfer_series_for(build_transfer_between(source, destination, Date.new(2026, 8, 3)))+ end++ test "Cleaner does not let a transfer allocated to another series keep a stale series alive" do+ source = @account+ destination = accounts(:credit_card)+ stale = RecurringTransaction.create_from_transfer(build_transfer_between(source, destination, Date.new(2026, 1, 1)))+ live = RecurringTransaction.create_from_transfer(build_transfer_between(source, destination, Date.new(2026, 1, 2)))+ stale.update!(last_occurrence_date: 7.months.ago.to_date)+ live.update!(last_occurrence_date: Date.current)++ # The stopped series' tolerance window still covers the live series' day.+ recent = 1.month.ago.to_date.beginning_of_month + 1.day+ entry = build_transfer_between(source, destination, recent).outflow_transaction.entry+ occurrence = live.recurring_occurrences.create!(+ family: @family, original_due_on: recent, due_on: recent, expected_amount: live.amount, currency: "USD", status: "scheduled"+ )+ occurrence.allocations.create!(+ entry: entry, allocated_amount: live.amount, currency: "USD", state: "confirmed", source: "auto_matched"+ )++ assert_includes stale.matching_transactions.map(&:id), entry.id++ RecurringTransaction.cleanup_stale_for(@family)++ assert_equal "inactive", stale.reload.status+ assert_equal "active", live.reload.status+ end++ test "Cleaner keeps a series alive on a transfer nothing else has claimed" do+ source = @account+ destination = accounts(:credit_card)+ series = RecurringTransaction.create_from_transfer(build_transfer_between(source, destination, Date.new(2026, 1, 1)))+ series.update!(last_occurrence_date: 7.months.ago.to_date)+ build_transfer_between(source, destination, 1.month.ago.to_date.beginning_of_month)++ RecurringTransaction.cleanup_stale_for(@family)++ assert_equal "active", series.reload.status+ end++ test "transfer_series_for ignores a monthly series whose schedule skips the date" do+ source = @account+ destination = accounts(:credit_card)+ series = RecurringTransaction.create_from_transfer(build_transfer_between(source, destination, Date.new(2026, 1, 31)))+ series.update!(weekend_adjust: "skip")+ saturday = Date.new(2026, 2, 28)++ assert_not series.schedule.matches_day?(saturday)+ assert_nil RecurringTransaction.transfer_series_for(build_transfer_between(source, destination, saturday))+ end++ test "an exact day beats a clamped day when both are equally close" do+ source = @account+ destination = accounts(:credit_card)+ day31 = RecurringTransaction.create_from_transfer(build_transfer_between(source, destination, Date.new(2026, 1, 31)))+ day28 = RecurringTransaction.create_from_transfer(build_transfer_between(source, destination, Date.new(2026, 1, 28)))+ # Ids decide ties otherwise: give the day-28 series the losing one.+ [ day31, day28 ].each { |series| series.recurring_occurrences.delete_all }+ day31.update_column(:id, "00000000-0000-4000-8000-000000000031")+ day28.update_column(:id, "ffffffff-ffff-4fff-8fff-ffffffffff28")+ day28 = RecurringTransaction.find(day28.id)++ assert_equal day28, RecurringTransaction.transfer_series_for(build_transfer_between(source, destination, Date.new(2026, 2, 28)))+ end++ test "transfer_series_for measures the day across the month boundary" do+ source = @account+ destination = accounts(:credit_card)+ day31 = RecurringTransaction.create_from_transfer(build_transfer_between(source, destination, Date.new(2026, 1, 31)))+ RecurringTransaction.create_from_transfer(build_transfer_between(source, destination, Date.new(2026, 1, 3)))++ # May 1 is one day from the day-31 series' April 30 occurrence, two from day 3.+ assert_equal day31, RecurringTransaction.transfer_series_for(build_transfer_between(source, destination, Date.new(2026, 5, 1)))+ end+test "projected_entry exposes source and destination on a recurring transfer" dodestination = accounts(:credit_card)rt = @family.recurring_transactions.create!(@@ -2260,6 +2423,18 @@ class RecurringTransactionTest < ActiveSupport::TestCase)end+ def build_transfer_between(source, destination, date, amount: 2000)+ outflow = source.entries.create!(+ date: date, amount: amount, currency: "USD", name: "raw",+ entryable: Transaction.new(kind: "standard")+ )+ inflow = destination.entries.create!(+ date: date, amount: -amount, currency: "USD", name: "raw",+ entryable: Transaction.new(kind: "standard")+ )+ Transfer.create!(outflow_transaction: outflow.entryable, inflow_transaction: inflow.entryable)+ end+def create_transfer_series(name, destination)@family.recurring_transactions.create!(name: name, account: @account, destination_account: destination, amount: 100, currency: "USD",