The personal finance app for everyone (by everyone)
Ruby
feat(recurring): allow marking transfers as recurring (#895) (#1589)
Guillem Arias Fauste7c06fe6296ad
diff --git a/app/controllers/transfers_controller.rb b/app/controllers/transfers_controller.rbindex 255ffb86b1..465891f2f4 100644--- a/app/controllers/transfers_controller.rb+++ b/app/controllers/transfers_controller.rb@@ -1,7 +1,7 @@class TransfersController < ApplicationControllerinclude StreamExtensions- before_action :set_transfer, only: %i[show destroy update]+ before_action :set_transfer, only: %i[show destroy update mark_as_recurring]before_action :set_accounts, only: %i[new create]def new@@ -11,6 +11,17 @@ class TransfersController < ApplicationControllerdef show@categories = Current.family.categories.alphabetically++ # Whether the current user can hit `mark_as_recurring`: feature flag on,+ # AND they have write access to BOTH transfer endpoints. Gating the+ # view button on this avoids showing a CTA that the controller would+ # reject via `require_account_permission!` for read-only sharers.+ endpoint_ids = [ @transfer.from_account&.id, @transfer.to_account&.id ].compact+ writable_endpoint_count = Account.writable_by(Current.user).where(id: endpoint_ids).distinct.count+ @can_mark_as_recurring_transfer =+ !Current.family.recurring_transactions_disabled? &&+ endpoint_ids.size == 2 &&+ writable_endpoint_count == 2enddef create@@ -75,6 +86,65 @@ class TransfersController < ApplicationControllerredirect_back_or_to transactions_url, notice: t(".success")end+ def mark_as_recurring+ if Current.family.recurring_transactions_disabled?+ flash[:alert] = t("recurring_transactions.transfer_feature_disabled")+ redirect_back_or_to transactions_path+ return+ end++ source_account = @transfer.from_account+ destination_account = @transfer.to_account++ if source_account.nil? || destination_account.nil?+ flash[:alert] = t("recurring_transactions.unexpected_error")+ redirect_back_or_to transactions_path+ return+ end++ return 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+ flash[:alert] = t("recurring_transactions.transfer_already_exists")+ respond_to do |format|+ format.html { redirect_back_or_to transactions_path }+ end+ return+ end++ begin+ RecurringTransaction.create_from_transfer(@transfer)+ flash[:notice] = t("recurring_transactions.transfer_marked_as_recurring")+ respond_to do |format|+ format.html { redirect_back_or_to transactions_path }+ end+ rescue 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")+ respond_to do |format|+ format.html { redirect_back_or_to transactions_path }+ end+ rescue StandardError => e+ Rails.logger.error(+ "transfers#mark_as_recurring failed: #{e.class} #{e.message} " \+ "(transfer=#{@transfer&.id} family=#{Current.family&.id} user=#{Current.user&.id})"+ )+ flash[:alert] = t("recurring_transactions.unexpected_error")+ respond_to do |format|+ format.html { redirect_back_or_to transactions_path }+ end+ end+ end+privatedef set_transfer# Finds the transfer and ensures the user has access to itdiff --git a/app/models/account.rb b/app/models/account.rbindex 0c50e1f70d..c5363ced40 100644--- a/app/models/account.rb+++ b/app/models/account.rb@@ -20,6 +20,14 @@ class Account < ApplicationRecordhas_many :holdings, dependent: :destroyhas_many :balances, dependent: :destroyhas_many :recurring_transactions, dependent: :destroy+ # Inverse for recurring transfers where this account is the destination.+ # Account#recurring_transactions only matches account_id; without this+ # association, destroying the destination account would hit the FK+ # cascade silently and the AR cache wouldn't reflect the deletion.+ has_many :inbound_recurring_transfers,+ class_name: "RecurringTransaction",+ foreign_key: :destination_account_id,+ dependent: :destroymonetize :balance, :cash_balancediff --git a/app/models/recurring_transaction.rb b/app/models/recurring_transaction.rbindex 0b30e6bd77..ffc2c75be5 100644--- a/app/models/recurring_transaction.rb+++ b/app/models/recurring_transaction.rb@@ -3,6 +3,7 @@ class RecurringTransaction < ApplicationRecordbelongs_to :familybelongs_to :account, optional: true+ belongs_to :destination_account, optional: true, class_name: "Account"belongs_to :merchant, optional: truemonetize :amount@@ -19,6 +20,7 @@ class RecurringTransaction < ApplicationRecordvalidates :occurrence_count, numericality: { only_integer: true, greater_than_or_equal_to: 0 }validate :merchant_or_name_presentvalidate :amount_variance_consistency+ validate :transfer_endpoints_consistentdef merchant_or_name_presentif merchant_id.blank? && name.blank?@@ -36,10 +38,50 @@ class RecurringTransaction < ApplicationRecordendend+ # When this row represents a recurring transfer, both endpoints must be+ # present, belong to the same family, and not be the same account.+ def transfer_endpoints_consistent+ return if destination_account_id.blank?++ if account_id.blank?+ errors.add(:account, "must be present on a recurring transfer")+ elsif account.blank?+ # account_id references a row that was destroyed. Mirror the+ # destination_account.blank? branch so the source side surfaces a+ # normal validation error too.+ errors.add(:account, "must exist")+ elsif destination_account.blank?+ # destination_account_id references a row that was destroyed (or never+ # existed). Surface as a normal validation error instead of letting+ # the FK fire on save.+ errors.add(:destination_account, "must exist")+ elsif account_id == destination_account_id+ errors.add(:destination_account, "cannot be the same as the source account")+ elsif account.family_id != destination_account.family_id+ errors.add(:destination_account, "must belong to the same family as the source account")+ end+ end++ def transfer?+ destination_account_id.present?+ end+scope :for_family, ->(family) { where(family: family) }scope :expected_soon, -> { active.where("next_expected_date <= ?", 1.month.from_now) }scope :accessible_by, ->(user) {- where(account_id: Account.accessible_by(user).select(:id)).or(where(account_id: nil))+ accessible_account_ids = Account.accessible_by(user).select(:id)+ # A recurring row is accessible when:+ # * its account_id is in the user's accessible set or null (legacy rows+ # with no account scoping survive), AND+ # * its destination_account_id is also accessible OR null (so a recurring+ # transfer never leaks into the list of a user without access to BOTH+ # endpoints).+ where(account_id: accessible_account_ids)+ .or(where(account_id: nil))+ .merge(+ where(destination_account_id: accessible_account_ids)+ .or(where(destination_account_id: nil))+ )}# Class methods for identification and cleanup@@ -58,6 +100,44 @@ class RecurringTransaction < ApplicationRecordCleaner.new(family).cleanup_stale_transactionsend+ # 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+ # account-pair-shaped, not merchant-shaped.+ def self.create_from_transfer(transfer)+ outflow_entry = transfer.outflow_transaction&.entry+ inflow_entry = transfer.inflow_transaction&.entry++ raise ArgumentError, "transfer is missing one of its entries" unless outflow_entry && inflow_entry++ source_account = outflow_entry.account+ destination_account = inflow_entry.account+ family = source_account.family++ expected_day = outflow_entry.date.day+ next_expected = calculate_next_expected_date_from_today(expected_day)++ create!(+ family: family,+ account: source_account,+ destination_account: destination_account,+ merchant_id: nil,+ # Transfer#name yields "Payment to ..." for liability destinations+ # and "Transfer to ..." otherwise, matching Transfer::Creator's+ # name_prefix logic so the recurring row reads consistently with+ # the originating Transfer.+ name: transfer.name,+ amount: outflow_entry.amount, # positive (outflow), per Sure sign convention+ currency: outflow_entry.currency,+ expected_day_of_month: expected_day,+ last_occurrence_date: outflow_entry.date,+ next_expected_date: next_expected,+ status: "active",+ occurrence_count: 1,+ manual: true+ )+ end+# Create a manual recurring transaction from an existing transaction# Automatically calculates amount variance from past 6 months of matching transactionsdef self.create_from_transaction(transaction, date_variance: 2)@@ -313,7 +393,10 @@ class RecurringTransaction < ApplicationRecordamount_min: expected_amount_min,amount_max: expected_amount_max,amount_avg: expected_amount_avg,- has_variance: has_amount_variance?+ has_variance: has_amount_variance?,+ transfer: transfer?,+ source_account: account,+ destination_account: destination_account)enddiff --git a/app/models/recurring_transaction/cleaner.rb b/app/models/recurring_transaction/cleaner.rbindex 4aecbb3434..dd22dcb896 100644--- a/app/models/recurring_transaction/cleaner.rb+++ b/app/models/recurring_transaction/cleaner.rb@@ -7,11 +7,21 @@ class RecurringTransactionend# Mark recurring transactions as inactive if they haven't occurred recently- # Uses 2 months for automatic recurring, 6 months for manual recurring+ # Uses 2 months for automatic recurring, 6 months for manual recurring.+ #+ # Transfer rows (destination_account_id present) are skipped: their+ # `matching_transactions` helper looks at single-account name/amount+ # which never matches a Transfer pair, so the Cleaner would+ # incorrectly mark a still-recurring transfer inactive at the+ # 6-month threshold. Issue #1590 tracks pair-detection-aware+ # matching for recurring transfers.def cleanup_stale_transactionsstale_count = 0- family.recurring_transactions.active.find_each do |recurring_transaction|+ family.recurring_transactions+ .active+ .where(destination_account_id: nil)+ .find_each do |recurring_transaction|next unless recurring_transaction.should_be_inactive?# Determine threshold based on manual flagdiff --git a/app/models/recurring_transaction/identifier.rb b/app/models/recurring_transaction/identifier.rbindex 82834c26ad..bcb6656d4e 100644--- a/app/models/recurring_transaction/identifier.rb+++ b/app/models/recurring_transaction/identifier.rb@@ -10,14 +10,20 @@ class RecurringTransactiondef identify_recurring_patternsthree_months_ago = 3.months.ago.to_date- # Get all transactions from the last 3 months+ # Skip transfer-kind transactions: they're one half of a Transfer pair, so grouping them+ # under their single account would produce incoherent recurring "patterns" that don't+ # represent the underlying account-pair flow. Recurring transfers are tracked on a+ # different shape (RecurringTransaction with destination_account_id). Filtering at the+ # SQL level avoids loading and discarding transfer entries for a busy family.entries_with_transactions = family.entries+ .joins("INNER JOIN transactions ON transactions.id = entries.entryable_id").where(entryable_type: "Transaction").where("entries.date >= ?", three_months_ago)+ .where.not("transactions.kind": Transaction::TRANSFER_KINDS).includes(:entryable).to_a- # Group by merchant (if present) or name, along with amount (preserve sign) and currency+ # Group by merchant (if present) or name, along with amount (preserve sign) and currency.grouped_transactions = entries_with_transactions.select { |entry| entry.entryable.is_a?(Transaction) }.group_by do |entry|@@ -140,9 +146,17 @@ class RecurringTransactionrecurring_patterns.sizeend- # Update variance for existing manual recurring transactions+ # Update variance for existing manual recurring transactions.+ #+ # Transfer rows (destination_account_id present) are skipped: their+ # variance / occurrence tracking would need pair-detection across+ # both endpoints rather than the single-account name/merchant match+ # the helper performs. Issue #1590 tracks the proper Cleaner-aware+ # matching for recurring transfers.def update_manual_recurring_transactions(since_date)- family.recurring_transactions.where(manual: true, status: "active").find_each do |recurring|+ family.recurring_transactions+ .where(manual: true, status: "active", destination_account_id: nil)+ .find_each do |recurring|# Find matching transactions in the recent periodmatching_entries = RecurringTransaction.find_matching_transaction_entries(family: family,diff --git a/app/views/recurring_transactions/_projected_transaction.html.erb b/app/views/recurring_transactions/_projected_transaction.html.erbindex 3659e3fe20..bc8778469a 100644--- a/app/views/recurring_transactions/_projected_transaction.html.erb+++ b/app/views/recurring_transactions/_projected_transaction.html.erb@@ -56,6 +56,10 @@<div class="col-span-2 ml-auto text-right shrink-0"><% display_amount = recurring_transaction.manual? && recurring_transaction.expected_amount_avg.present? ? recurring_transaction.expected_amount_avg : recurring_transaction.amount %>- <%= content_tag :p, format_money(-Money.new(display_amount, recurring_transaction.currency)), class: ["font-medium", "privacy-sensitive", display_amount.negative? ? "text-success" : "text-subdued"] %>+ <% if recurring_transaction.transfer? %>+ <%= content_tag :p, format_money(Money.new(display_amount.abs, recurring_transaction.currency)), class: [ "font-medium", "privacy-sensitive", "text-secondary" ] %>+ <% else %>+ <%= content_tag :p, format_money(-Money.new(display_amount, recurring_transaction.currency)), class: ["font-medium", "privacy-sensitive", display_amount.negative? ? "text-success" : "text-subdued"] %>+ <% end %></div></div>diff --git a/app/views/recurring_transactions/index.html.erb b/app/views/recurring_transactions/index.html.erbindex 7447cb3172..96b29d4a10 100644--- a/app/views/recurring_transactions/index.html.erb+++ b/app/views/recurring_transactions/index.html.erb@@ -128,16 +128,22 @@<% end %></div></td>- <td class="py-3 px-2 text-sm font-medium privacy-sensitive <%= recurring_transaction.amount.negative? ? "text-success" : "text-primary" %>">- <% if recurring_transaction.manual? && recurring_transaction.has_amount_variance? %>- <div class="inline-flex items-center gap-1 cursor-help group" title="<%= t("recurring_transactions.amount_range", min: format_money(-recurring_transaction.expected_amount_min_money), max: format_money(-recurring_transaction.expected_amount_max_money)) %>">- <span class="text-xs text-secondary group-hover:text-primary transition-colors">~</span>- <span class="border-b border-dashed border-subdued group-hover:border-primary transition-colors privacy-sensitive"><%= format_money(-recurring_transaction.expected_amount_avg_money) %></span>- </div>- <% else %>- <%= format_money(-recurring_transaction.amount_money) %>- <% end %>- </td>+ <% if recurring_transaction.transfer? %>+ <td class="py-3 px-2 text-sm font-medium privacy-sensitive text-secondary">+ <%= format_money(recurring_transaction.amount_money.abs) %>+ </td>+ <% else %>+ <td class="py-3 px-2 text-sm font-medium privacy-sensitive <%= recurring_transaction.amount.negative? ? "text-success" : "text-primary" %>">+ <% if recurring_transaction.manual? && recurring_transaction.has_amount_variance? %>+ <div class="inline-flex items-center gap-1 cursor-help group" title="<%= t("recurring_transactions.amount_range", min: format_money(-recurring_transaction.expected_amount_min_money), max: format_money(-recurring_transaction.expected_amount_max_money)) %>">+ <span class="text-xs text-secondary group-hover:text-primary transition-colors">~</span>+ <span class="border-b border-dashed border-subdued group-hover:border-primary transition-colors privacy-sensitive"><%= format_money(-recurring_transaction.expected_amount_avg_money) %></span>+ </div>+ <% else %>+ <%= format_money(-recurring_transaction.amount_money) %>+ <% end %>+ </td>+ <% end %><td class="py-3 px-2 text-sm text-secondary"><%= t("recurring_transactions.day_of_month", day: recurring_transaction.expected_day_of_month) %></td>diff --git a/app/views/transfers/show.html.erb b/app/views/transfers/show.html.erbindex 792899bbb5..54705661fb 100644--- a/app/views/transfers/show.html.erb+++ b/app/views/transfers/show.html.erb@@ -73,6 +73,22 @@<% end %><% dialog.with_section(title: t(".settings")) do %><div class="pb-4">+ <% if @can_mark_as_recurring_transfer %>+ <div class="flex items-center justify-between gap-2 p-3">+ <div class="text-sm space-y-1">+ <h4 class="text-primary"><%= t(".mark_recurring_title") %></h4>+ <p class="text-secondary"><%= t(".mark_recurring_subtitle") %></p>+ </div>+ <%= render DS::Button.new(+ text: t(".mark_recurring"),+ variant: "outline",+ icon: "repeat",+ href: mark_as_recurring_transfer_path(@transfer),+ method: :post,+ frame: "_top"+ ) %>+ </div>+ <% end %><div class="flex items-center justify-between gap-2 p-3"><div class="text-sm space-y-1"><h4 class="text-primary"><%= t(".delete_title") %></h4>diff --git a/config/locales/views/recurring_transactions/en.yml b/config/locales/views/recurring_transactions/en.ymlindex 504d321d95..5d57c93061 100644--- a/config/locales/views/recurring_transactions/en.yml+++ b/config/locales/views/recurring_transactions/en.yml@@ -50,3 +50,7 @@ en:inactive: Inactivebadges:manual: Manual+ transfer_marked_as_recurring: Transfer marked as recurring+ transfer_already_exists: A recurring transfer already exists for this account pair+ transfer_creation_failed: Failed to create recurring transfer. Please check the transfer details and try again.+ transfer_feature_disabled: Recurring transactions are disabled for this familydiff --git a/config/locales/views/transfers/en.yml b/config/locales/views/transfers/en.ymlindex 9116f4f6b1..2eda135857 100644--- a/config/locales/views/transfers/en.yml+++ b/config/locales/views/transfers/en.yml@@ -31,6 +31,10 @@ en:transactions.delete_title: Remove transfer?details: Details+ mark_recurring: Mark as recurring+ mark_recurring_subtitle: Track this transfer as a recurring pattern in the upcoming+ feed and recurring page.+ mark_recurring_title: Mark transfer as recurringnote_label: Notesnote_placeholder: Add a note to this transferoverview: Overviewdiff --git a/config/routes.rb b/config/routes.rbindex 1ab28a7c17..a9fee8dd14 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -277,7 +277,11 @@ Rails.application.routes.draw doget :exchange_rate, to: "exchange_rates#show"- resources :transfers, only: %i[new create destroy show update]+ resources :transfers, only: %i[new create destroy show update] do+ member do+ post :mark_as_recurring+ end+ endresources :imports, only: %i[index new show create update destroy] domember dodiff --git a/db/migrate/20260429120000_add_destination_account_id_to_recurring_transactions.rb b/db/migrate/20260429120000_add_destination_account_id_to_recurring_transactions.rbnew file mode 100644index 0000000000..ab5df02e36--- /dev/null+++ b/db/migrate/20260429120000_add_destination_account_id_to_recurring_transactions.rb@@ -0,0 +1,107 @@+class AddDestinationAccountIdToRecurringTransactions < ActiveRecord::Migration[7.2]+ def up+ add_reference :recurring_transactions, :destination_account, type: :uuid, null: true,+ foreign_key: { to_table: :accounts, on_delete: :cascade }++ # Backfill cascade on the existing account_id FK while we're widening this+ # table -- consistent with the cascading direction set by+ # 20251030172500_add_cascade_on_account_deletes.rb. Without this, deleting+ # an Account that has any recurring_transactions referencing it raises FK+ # violations during Family destruction.+ remove_foreign_key :recurring_transactions, :accounts, column: :account_id+ add_foreign_key :recurring_transactions, :accounts, column: :account_id, on_delete: :cascade++ # Replace the partial unique indexes added by 20260326112218 with TWO+ # predicate-partitioned variants:+ #+ # * non-transfer rows (destination_account_id IS NULL) keep the+ # existing 5-column shape so behaviour is unchanged.+ # * transfer rows (destination_account_id IS NOT NULL) get a+ # 6-column variant that includes destination_account_id.+ #+ # We can't simply widen the index because Postgres treats NULLs as+ # distinct in unique indexes, so two non-transfer rows with the same+ # (family, account, merchant/name, amount, currency) but NULL+ # destination would no longer collide.+ remove_index :recurring_transactions, name: "idx_recurring_txns_acct_merchant", if_exists: true+ remove_index :recurring_transactions, name: "idx_recurring_txns_acct_name", if_exists: true++ add_index :recurring_transactions,+ [ :family_id, :account_id, :merchant_id, :amount, :currency ],+ unique: true,+ where: "merchant_id IS NOT NULL AND destination_account_id IS NULL",+ name: "idx_recurring_txns_acct_merchant"++ add_index :recurring_transactions,+ [ :family_id, :account_id, :name, :amount, :currency ],+ unique: true,+ where: "name IS NOT NULL AND merchant_id IS NULL AND destination_account_id IS NULL",+ name: "idx_recurring_txns_acct_name"++ add_index :recurring_transactions,+ [ :family_id, :account_id, :destination_account_id, :merchant_id, :amount, :currency ],+ unique: true,+ where: "destination_account_id IS NOT NULL AND merchant_id IS NOT NULL",+ name: "idx_recurring_txns_pair_merchant"++ add_index :recurring_transactions,+ [ :family_id, :account_id, :destination_account_id, :name, :amount, :currency ],+ unique: true,+ where: "destination_account_id IS NOT NULL AND name IS NOT NULL AND merchant_id IS NULL",+ name: "idx_recurring_txns_pair_name"++ # Enforce transfer invariants in the database alongside the model+ # validations. Per CLAUDE.md: "Enforce null checks, unique indexes,+ # and simple validations in the database schema for PostgreSQL".+ add_check_constraint :recurring_transactions,+ "destination_account_id IS NULL OR account_id IS NOT NULL",+ name: "chk_recurring_txns_transfer_requires_source"++ add_check_constraint :recurring_transactions,+ "destination_account_id IS NULL OR destination_account_id <> account_id",+ name: "chk_recurring_txns_transfer_distinct_accounts"+ end++ def down+ # Transfer rows depend on destination_account_id, which the legacy+ # schema doesn't model. Re-adding the legacy unique indexes after+ # transfer rows exist would violate uniqueness on otherwise-identical+ # (family, account, merchant/name, amount, currency) tuples that+ # differ only by destination, so we drop transfer rows before+ # restoring the old shape. Down migrations are expected to lose+ # feature-specific data; the column itself is removed below anyway.+ execute <<~SQL+ DELETE FROM recurring_transactions+ WHERE destination_account_id IS NOT NULL+ SQL++ remove_check_constraint :recurring_transactions, name: "chk_recurring_txns_transfer_requires_source"+ remove_check_constraint :recurring_transactions, name: "chk_recurring_txns_transfer_distinct_accounts"++ remove_index :recurring_transactions, name: "idx_recurring_txns_pair_merchant", if_exists: true+ remove_index :recurring_transactions, name: "idx_recurring_txns_pair_name", if_exists: true+ remove_index :recurring_transactions, name: "idx_recurring_txns_acct_merchant", if_exists: true+ remove_index :recurring_transactions, name: "idx_recurring_txns_acct_name", if_exists: true++ add_index :recurring_transactions,+ [ :family_id, :account_id, :merchant_id, :amount, :currency ],+ unique: true,+ where: "merchant_id IS NOT NULL",+ name: "idx_recurring_txns_acct_merchant"++ add_index :recurring_transactions,+ [ :family_id, :account_id, :name, :amount, :currency ],+ unique: true,+ where: "name IS NOT NULL AND merchant_id IS NULL",+ name: "idx_recurring_txns_acct_name"++ remove_foreign_key :recurring_transactions, :accounts, column: :account_id+ add_foreign_key :recurring_transactions, :accounts, column: :account_id++ # Drop the destination_account_id FK by referencing the actual `accounts`+ # table; Rails would otherwise infer the table as `destination_accounts`+ # (the pluralised reference name) and fail with `no foreign key`.+ remove_foreign_key :recurring_transactions, column: :destination_account_id+ remove_reference :recurring_transactions, :destination_account+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 1dbf42e987..ecd756f91a 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -1194,13 +1194,19 @@ ActiveRecord::Schema[7.2].define(version: 2026_05_11_090000) dot.decimal "expected_amount_max", precision: 19, scale: 4t.decimal "expected_amount_avg", precision: 19, scale: 4t.uuid "account_id"+ t.uuid "destination_account_id"t.index ["account_id"], name: "index_recurring_transactions_on_account_id"- t.index ["family_id", "account_id", "merchant_id", "amount", "currency"], name: "idx_recurring_txns_acct_merchant", unique: true, where: "(merchant_id IS NOT NULL)"- t.index ["family_id", "account_id", "name", "amount", "currency"], name: "idx_recurring_txns_acct_name", unique: true, where: "((name IS NOT NULL) AND (merchant_id IS NULL))"+ t.index ["destination_account_id"], name: "index_recurring_transactions_on_destination_account_id"+ t.index ["family_id", "account_id", "destination_account_id", "merchant_id", "amount", "currency"], name: "idx_recurring_txns_pair_merchant", unique: true, where: "((destination_account_id IS NOT NULL) AND (merchant_id IS NOT NULL))"+ t.index ["family_id", "account_id", "destination_account_id", "name", "amount", "currency"], name: "idx_recurring_txns_pair_name", unique: true, where: "((destination_account_id IS NOT NULL) AND (name IS NOT NULL) AND (merchant_id IS NULL))"+ t.index ["family_id", "account_id", "merchant_id", "amount", "currency"], name: "idx_recurring_txns_acct_merchant", unique: true, where: "((merchant_id IS NOT NULL) AND (destination_account_id IS NULL))"+ t.index ["family_id", "account_id", "name", "amount", "currency"], name: "idx_recurring_txns_acct_name", unique: true, where: "((name IS NOT NULL) AND (merchant_id IS NULL) AND (destination_account_id IS NULL))"t.index ["family_id", "status"], name: "index_recurring_transactions_on_family_id_and_status"t.index ["family_id"], name: "index_recurring_transactions_on_family_id"t.index ["merchant_id"], name: "index_recurring_transactions_on_merchant_id"t.index ["next_expected_date"], name: "index_recurring_transactions_on_next_expected_date"+ t.check_constraint "destination_account_id IS NULL OR account_id IS NOT NULL", name: "chk_recurring_txns_transfer_requires_source"+ t.check_constraint "destination_account_id IS NULL OR destination_account_id <> account_id", name: "chk_recurring_txns_transfer_distinct_accounts"endcreate_table "rejected_transfers", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|@@ -1288,7 +1294,7 @@ ActiveRecord::Schema[7.2].define(version: 2026_05_11_090000) dot.index ["kind"], name: "index_securities_on_kind"t.index ["price_provider", "offline_reason"], name: "index_securities_on_price_provider_and_offline_reason"t.index ["price_provider"], name: "index_securities_on_price_provider"- t.check_constraint "kind::text = ANY (ARRAY['standard'::character varying, 'cash'::character varying]::text[])", name: "chk_securities_kind"+ t.check_constraint "kind::text = ANY (ARRAY['standard'::character varying::text, 'cash'::character varying::text])", name: "chk_securities_kind"endcreate_table "security_prices", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|@@ -1447,8 +1453,8 @@ ActiveRecord::Schema[7.2].define(version: 2026_05_11_090000) dot.datetime "updated_at", null: falset.boolean "manual_sync", default: false, null: falset.index ["account_id"], name: "index_sophtron_accounts_on_account_id"- t.index ["sophtron_item_id"], name: "index_sophtron_accounts_on_sophtron_item_id"t.index ["sophtron_item_id", "account_id"], name: "idx_unique_sophtron_accounts_per_item", unique: true+ t.index ["sophtron_item_id"], name: "index_sophtron_accounts_on_sophtron_item_id"endcreate_table "sophtron_items", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|@@ -1772,7 +1778,8 @@ ActiveRecord::Schema[7.2].define(version: 2026_05_11_090000) doadd_foreign_key "oidc_identities", "users"add_foreign_key "plaid_accounts", "plaid_items"add_foreign_key "plaid_items", "families"- add_foreign_key "recurring_transactions", "accounts"+ add_foreign_key "recurring_transactions", "accounts", column: "destination_account_id", on_delete: :cascade+ add_foreign_key "recurring_transactions", "accounts", on_delete: :cascadeadd_foreign_key "recurring_transactions", "families"add_foreign_key "recurring_transactions", "merchants"add_foreign_key "rejected_transfers", "transactions", column: "inflow_transaction_id"diff --git a/test/controllers/transfers_controller_test.rb b/test/controllers/transfers_controller_test.rbindex ca42a51fa4..544b100572 100644--- a/test/controllers/transfers_controller_test.rb+++ b/test/controllers/transfers_controller_test.rb@@ -198,4 +198,48 @@ class TransfersControllerTest < ActionDispatch::IntegrationTesttransfer.reloadendend++ test "mark_as_recurring creates a recurring transfer" do+ transfer = transfers(:one)+ family = users(:family_admin).family+ family.recurring_transactions.destroy_all++ assert_difference -> { RecurringTransaction.where(family: family).count }, +1 do+ post mark_as_recurring_transfer_url(transfer)+ end++ rt = RecurringTransaction.where(family: family).last+ assert rt.transfer?+ assert_equal transfer.outflow_transaction.entry.account, rt.account+ assert_equal transfer.inflow_transaction.entry.account, rt.destination_account+ assert rt.manual?+ assert_equal I18n.t("recurring_transactions.transfer_marked_as_recurring"), flash[:notice]+ assert_redirected_to transactions_path+ end++ test "mark_as_recurring is idempotent: second call flashes already-exists" do+ transfer = transfers(:one)+ family = users(:family_admin).family+ family.recurring_transactions.destroy_all++ post mark_as_recurring_transfer_url(transfer)+ assert_equal I18n.t("recurring_transactions.transfer_marked_as_recurring"), flash[:notice]++ 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" do+ transfer = transfers(:one)+ family = users(:family_admin).family+ family.update!(recurring_transactions_disabled: true)+ family.recurring_transactions.destroy_all++ assert_no_difference -> { RecurringTransaction.where(family: family).count } do+ post mark_as_recurring_transfer_url(transfer)+ end+ assert_equal I18n.t("recurring_transactions.transfer_feature_disabled"), flash[:alert]+ endenddiff --git a/test/models/recurring_transaction_test.rb b/test/models/recurring_transaction_test.rbindex 6c469eb83b..20c8a28ae7 100644--- a/test/models/recurring_transaction_test.rb+++ b/test/models/recurring_transaction_test.rb@@ -738,4 +738,326 @@ class RecurringTransactionTest < ActiveSupport::TestCaseassert recurring_b.present?assert_not_equal recurring_a, recurring_bend++ # ----- Recurring transfers (issue #895 / discussion #1224) -----++ test "transfer? is false when destination_account is absent" do+ rt = @family.recurring_transactions.create!(+ account: @account,+ name: "Spotify",+ amount: 9.99,+ currency: "USD",+ expected_day_of_month: 5,+ last_occurrence_date: Date.current,+ next_expected_date: 5.days.from_now.to_date,+ manual: true+ )+ assert_not rt.transfer?+ end++ test "transfer? is true when destination_account is present" do+ destination = accounts(:credit_card)+ rt = @family.recurring_transactions.create!(+ account: @account,+ destination_account: destination,+ name: "Transfer to #{destination.name}",+ amount: 500,+ currency: "USD",+ expected_day_of_month: 1,+ last_occurrence_date: Date.current,+ next_expected_date: 1.month.from_now.to_date,+ manual: true+ )+ assert rt.transfer?+ end++ test "validation rejects same source and destination accounts" do+ rt = @family.recurring_transactions.build(+ account: @account,+ destination_account: @account,+ name: "Self-transfer",+ amount: 100,+ currency: "USD",+ expected_day_of_month: 1,+ last_occurrence_date: Date.current,+ next_expected_date: 1.month.from_now.to_date,+ manual: true+ )+ assert_not rt.valid?+ assert_includes rt.errors[:destination_account], "cannot be the same as the source account"+ end++ test "validation rejects dangling source account_id (account does not exist)" do+ rt = @family.recurring_transactions.build(+ account_id: SecureRandom.uuid, # references nothing+ destination_account: accounts(:credit_card),+ name: "Phantom source",+ amount: 100,+ currency: "USD",+ expected_day_of_month: 1,+ last_occurrence_date: Date.current,+ next_expected_date: 1.month.from_now.to_date,+ manual: true+ )+ assert_not rt.valid?+ assert_includes rt.errors[:account], "must exist"+ end++ test "validation rejects dangling destination_account_id (account does not exist)" do+ rt = @family.recurring_transactions.build(+ account: @account,+ destination_account_id: SecureRandom.uuid, # references nothing+ name: "Phantom transfer",+ amount: 100,+ currency: "USD",+ expected_day_of_month: 1,+ last_occurrence_date: Date.current,+ next_expected_date: 1.month.from_now.to_date,+ manual: true+ )+ assert_not rt.valid?+ assert_includes rt.errors[:destination_account], "must exist"+ end++ test "validation rejects destination on different family" do+ other_family = Family.create!(name: "Other", locale: "en", date_format: "%Y-%m-%d", currency: "USD")+ other_account = other_family.accounts.create!(name: "Other depository", balance: 0, currency: "USD", accountable: Depository.new)++ rt = @family.recurring_transactions.build(+ account: @account,+ destination_account: other_account,+ name: "Foreign transfer",+ amount: 100,+ currency: "USD",+ expected_day_of_month: 1,+ last_occurrence_date: Date.current,+ next_expected_date: 1.month.from_now.to_date,+ manual: true+ )+ assert_not rt.valid?+ assert_includes rt.errors[:destination_account], "must belong to the same family as the source account"+ end++ test "create_from_transfer builds a recurring transfer with both endpoints" do+ source = @account+ destination = accounts(:credit_card)++ outflow_entry = source.entries.create!(+ date: 5.days.ago.to_date, amount: 250, currency: "USD",+ name: "Manual transfer",+ entryable: Transaction.new(kind: "standard")+ )+ inflow_entry = destination.entries.create!(+ date: 5.days.ago.to_date, amount: -250, currency: "USD",+ name: "Manual transfer",+ entryable: Transaction.new(kind: "standard")+ )+ transfer = Transfer.create!(+ outflow_transaction: outflow_entry.entryable,+ inflow_transaction: inflow_entry.entryable+ )++ rt = RecurringTransaction.create_from_transfer(transfer)++ assert rt.transfer?+ assert_equal source, rt.account+ assert_equal destination, rt.destination_account+ assert_equal 250, rt.amount+ assert_equal "USD", rt.currency+ assert_equal 5.days.ago.to_date.day, rt.expected_day_of_month+ assert rt.manual?+ assert_equal "active", rt.status+ end++ test "projected_entry exposes source and destination on a recurring transfer" do+ destination = accounts(:credit_card)+ rt = @family.recurring_transactions.create!(+ account: @account,+ destination_account: destination,+ name: "Transfer to #{destination.name}",+ amount: 500,+ currency: "USD",+ expected_day_of_month: 15,+ last_occurrence_date: Date.current,+ next_expected_date: 15.days.from_now.to_date,+ manual: true+ )++ projected = rt.projected_entry+ assert projected.transfer+ assert_equal @account, projected.source_account+ assert_equal destination, projected.destination_account+ assert_equal 500, projected.amount+ assert_equal "USD", projected.currency+ end++ test "Identifier skips transfer-kind transactions" do+ # Three depository transactions tagged as funds_movement (e.g. they're+ # one half of a Transfer pair). Identifier shouldn't latch onto these+ # as a single-account "pattern" because the underlying flow is two-+ # account and is tracked on a different shape (destination_account_id).+ [ 0, 1, 2 ].each do |months_ago|+ transaction = Transaction.create!(merchant: @merchant, kind: "funds_movement")+ @account.entries.create!(+ date: months_ago.months.ago.beginning_of_month + 5.days,+ amount: 50.00,+ currency: "USD",+ name: "Recurring transfer half",+ entryable: transaction+ )+ end++ assert_no_difference "@family.recurring_transactions.count" do+ RecurringTransaction.identify_patterns_for!(@family)+ end+ end++ test "Identifier creates a pattern from expense halves while ignoring co-resident transfer halves" do+ # Same merchant, amount, day-of-month: 3 standard expenses + 3 transfer halves.+ # Without the TRANSFER_KINDS filter, the identifier would either double-count+ # (six occurrences) or surface a weird pattern. With the filter, only the+ # expense pattern is created.+ [ 0, 1, 2 ].each do |months_ago|+ base_date = months_ago.months.ago.beginning_of_month + 5.days++ @account.entries.create!(+ date: base_date, amount: 50.00, currency: "USD", name: "Coffee",+ entryable: Transaction.create!(merchant: @merchant, kind: "standard")+ )+ @account.entries.create!(+ date: base_date, amount: 50.00, currency: "USD", name: "Half of transfer",+ entryable: Transaction.create!(merchant: @merchant, kind: "funds_movement")+ )+ end++ assert_difference "@family.recurring_transactions.count", 1 do+ RecurringTransaction.identify_patterns_for!(@family)+ end+ assert_nil @family.recurring_transactions.last.destination_account_id+ end++ test "create_from_transfer name reflects Transfer#name (Payment vs Transfer based on destination)" do+ # Transfer#name returns "Payment to ..." for liability destinations+ # and "Transfer to ..." otherwise, mirroring Transfer::Creator's+ # name_prefix logic. The recurring row should pick that up rather+ # than hard-coding "Transfer to ...".+ source = @account+ cc_destination = accounts(:credit_card) # liability+ outflow = source.entries.create!(+ date: 5.days.ago.to_date, amount: 100, currency: "USD",+ name: "raw", entryable: Transaction.new(kind: "standard")+ )+ inflow = cc_destination.entries.create!(+ date: 5.days.ago.to_date, amount: -100, currency: "USD",+ name: "raw", entryable: Transaction.new(kind: "standard")+ )+ transfer = Transfer.create!(+ outflow_transaction: outflow.entryable, inflow_transaction: inflow.entryable+ )++ rt = RecurringTransaction.create_from_transfer(transfer)+ assert_equal "Payment to #{cc_destination.name}", rt.name+ end++ test "create_from_transfer stores source-side currency on multi-currency transfers" do+ source = @account # USD depository+ destination = @family.accounts.create!(+ name: "EUR cash", balance: 0, currency: "EUR", accountable: Depository.new+ )+ outflow_entry = source.entries.create!(+ date: 5.days.ago.to_date, amount: 100, currency: "USD",+ name: "FX transfer", entryable: Transaction.new(kind: "standard")+ )+ inflow_entry = destination.entries.create!(+ date: 5.days.ago.to_date, amount: -92, currency: "EUR",+ name: "FX transfer", entryable: Transaction.new(kind: "standard")+ )+ transfer = Transfer.create!(+ outflow_transaction: outflow_entry.entryable,+ inflow_transaction: inflow_entry.entryable+ )++ rt = RecurringTransaction.create_from_transfer(transfer)+ assert_equal "USD", rt.currency, "stores source-side currency"+ assert_equal 100, rt.amount, "stores source-side amount"+ end++ test "destroying the destination account cascades to inbound recurring transfers" do+ source = @account+ destination = accounts(:credit_card)+ rt = @family.recurring_transactions.create!(+ account: source, destination_account: destination,+ name: "Transfer to CC", amount: 250, currency: "USD",+ expected_day_of_month: 1, last_occurrence_date: Date.current,+ next_expected_date: 1.month.from_now.to_date, manual: true+ )++ assert_difference -> { RecurringTransaction.count }, -1 do+ destination.destroy+ end+ assert_not RecurringTransaction.exists?(rt.id)+ end++ test "Cleaner skips recurring transfers so they aren't mistakenly marked inactive" do+ # `matching_transactions` is single-account name/amount-based and never+ # matches a Transfer pair, so without the skip the recurring transfer+ # would flip to inactive at the 6-month threshold even when the user+ # is still doing the transfer monthly. Issue #1590 tracks the proper+ # pair-detection fix.+ rt = @family.recurring_transactions.create!(+ account: @account, destination_account: accounts(:credit_card),+ name: "Transfer to CC", amount: 250, currency: "USD",+ expected_day_of_month: 5,+ last_occurrence_date: 7.months.ago.to_date,+ next_expected_date: 5.days.from_now.to_date,+ manual: true+ )+ assert rt.should_be_inactive?, "guard sanity: row would be marked inactive without the skip"++ RecurringTransaction.cleanup_stale_for(@family)+ assert_equal "active", rt.reload.status+ end++ test "Identifier#update_manual_recurring_transactions skips recurring transfers" do+ # Same reasoning as the Cleaner skip. Without the guard, the helper+ # would call find_matching_transaction_entries (single-account, by+ # name) on a transfer row and silently overwrite its variance /+ # occurrence_count with []. The variance fields should stay nil.+ rt = @family.recurring_transactions.create!(+ account: @account, destination_account: accounts(:credit_card),+ name: "Transfer to CC", amount: 500, currency: "USD",+ expected_day_of_month: 1,+ last_occurrence_date: Date.current,+ next_expected_date: 1.month.from_now.to_date,+ manual: true,+ occurrence_count: 7+ )++ RecurringTransaction.identify_patterns_for!(@family)++ rt.reload+ assert_nil rt.expected_amount_min+ assert_nil rt.expected_amount_max+ assert_nil rt.expected_amount_avg+ assert_equal 7, rt.occurrence_count, "occurrence_count must not be overwritten by the manual-recurring update path"+ end++ test "unique partial index still de-duplicates non-transfer recurring rows after destination widening" do+ base_attrs = {+ account: @account,+ merchant: @merchant,+ amount: 15.99,+ currency: "USD",+ expected_day_of_month: 5,+ last_occurrence_date: Date.current,+ next_expected_date: 1.month.from_now.to_date,+ manual: false,+ occurrence_count: 3+ }+ @family.recurring_transactions.create!(base_attrs)++ assert_raises(ActiveRecord::RecordNotUnique) do+ @family.recurring_transactions.create!(base_attrs)+ end+ endend