The personal finance app for everyone (by everyone)
Ruby
Check for an existing bill before creating one from a transaction (#4375)
jaysbeekay533a48c80998
diff --git a/app/controllers/recurring_transactions_controller.rb b/app/controllers/recurring_transactions_controller.rbindex bde75c6246..f21fc3aff7 100644--- a/app/controllers/recurring_transactions_controller.rb+++ b/app/controllers/recurring_transactions_controller.rb@@ -19,6 +19,8 @@ class RecurringTransactionsController < ApplicationControllerbefore_action :set_recurring_transaction, only: %i[edit update toggle_status destroy confirm dismiss]before_action :ensure_series_writable, only: %i[update toggle_status destroy confirm dismiss]+ helper_method :series_writable?, :separate_bill_chosen?+def indexscope = Current.family.recurring_transactions.accessible_by(Current.user)@@ -142,7 +144,27 @@ class RecurringTransactionsController < ApplicationControllerdef create@recurring_transaction = build_declared_bill- if @recurring_transaction.errors.none? && save_declared_bill+ # The posted fields carry only a name, and a detected bill is keyed by+ # merchant with no name, so whether this duplicates a bill is asked of the+ # transaction the dialog was opened from. The dialog already said so; this+ # catches a stale dialog or a direct POST. The check and the save hold the+ # entry lock the Allocator takes, so neither a second submission, an+ # allocation of this transaction nor a "Mark as recurring" on it can slip+ # in between them. The lock is transaction-scoped, so it is taken inside+ # the class-level transaction (Entry#transaction is the delegated-type+ # reader, not ActiveRecord's).+ @source_entry = Current.accessible_entries.find_by(id: params[:entry_id])+ saved = if @source_entry && !separate_bill_chosen?+ Entry.transaction do+ RecurringTransaction::Allocator.lock_entry!(@source_entry)+ @covering_series = covering_series_for(@source_entry)+ @covering_series.nil? && @recurring_transaction.errors.none? && save_declared_bill+ end+ else+ @recurring_transaction.errors.none? && save_declared_bill+ end++ if savedflash[:notice] = @recurring_transaction.typed_income? ? t(".success_income") : t(".success")respond_to do |format|@@ -246,6 +268,8 @@ class RecurringTransactionsController < ApplicationController# smart-fill path, so a failed suggestion still leaves the user exactly# where the plain prefill would have.def prefill_recurring_from_entry(entry)+ @source_entry = entry+ @covering_series = covering_series_for(entry)@recurring_transaction.name = entry.entryable.try(:merchant)&.name.presence || entry.name@recurring_transaction.amount = entry.amount.abs@recurring_transaction.currency = entry.currency@@ -258,6 +282,19 @@ class RecurringTransactionsController < ApplicationControllerprivate+ # "Create a separate bill anyway" posts allow_duplicate=1, and only that+ # counts as the choice: a "0" or "false" from a direct POST does not.+ def separate_bill_chosen?+ params[:allow_duplicate] == "1"+ end++ # Only a bill this user can open is worth naming in the dialog.+ def covering_series_for(entry)+ return unless entry.transaction?++ Current.family.recurring_transactions.accessible_by(Current.user).covering(entry)+ end+# Sign-filtered detected patterns not yet covered by any series, mapped# to what the picker renders. Each candidate carries its latest entry's# id so selection can ride the existing entry_id prefill path. Patterns@@ -342,10 +379,11 @@ class RecurringTransactionsController < ApplicationController# Accountless series carry no account gate. Same contract as# RecurringOccurrencesController#ensure_series_writable.def ensure_series_writable- return if @recurring_transaction.account_id.nil?- return if Account.writable_by(Current.user).where(id: @recurring_transaction.account_id).exists?+ raise ActiveRecord::RecordNotFound unless series_writable?(@recurring_transaction)+ end- raise ActiveRecord::RecordNotFound+ def series_writable?(series)+ series.account_id.nil? || Account.writable_by(Current.user).where(id: series.account_id).exists?end# name, amount and account are handled by apply_editable_identity ratherdiff --git a/app/controllers/transactions_controller.rb b/app/controllers/transactions_controller.rbindex 3e1f590541..08a4df3b22 100644--- a/app/controllers/transactions_controller.rb+++ b/app/controllers/transactions_controller.rb@@ -454,19 +454,24 @@ class TransactionsController < ApplicationControllerreturn unless require_account_permission!(transaction.entry.account)- # Check if a recurring transaction already exists for this pattern.- # The UI disables the button ahead of time using the same lookup, but this- # guard remains as the authoritative check (e.g. stale page, direct POST).- existing = transaction.existing_manual_recurring_transaction-- if existing- flash[:alert] = t("recurring_transactions.already_exists")- redirect_back_or_to transactions_path- return- end-begin- recurring_transaction = RecurringTransaction.create_from_transaction(transaction)+ # Check if a recurring transaction already exists for this pattern.+ # The UI disables the button ahead of time using the same lookup, but+ # this guard remains as the authoritative check (e.g. stale page, direct+ # POST). The check and the create hold the entry lock the Allocator and+ # the add-bill form take, so neither can slip in between them.+ blocked = nil+ Entry.transaction do+ RecurringTransaction::Allocator.lock_entry!(transaction.entry)+ blocked = mark_recurring_blocked_message(transaction)+ RecurringTransaction.create_from_transaction(transaction) unless blocked+ end++ if blocked+ flash[:alert] = blocked+ redirect_back_or_to transactions_path+ return+ endrespond_to do |format|format.html do@@ -526,47 +531,40 @@ class TransactionsController < ApplicationControllerendprivate- # Scoped by user (not just family) because Current.accessible_entries is- # user-scoped for family sharing (see Current#accessible_entries).- #- # Includes Family#accounts_status_version because `uncategorized_transactions`- # filters on account status (draft/active), and toggling an account's- # active status (AccountsController#toggle_active) doesn't touch `entries`- # or `AccountShare`, so it wouldn't otherwise bust this cache.def uncategorized_count_cache_key"transactions_uncategorized_count/v5/#{Current.family.id}/#{Current.user.id}/" \"#{Current.family.entries_version}/#{Current.family.accounts_status_version}/#{Current.account_share_version}"end- # Scoped additionally by Date.current since the "next 10 days" window is- # date-dependent and would otherwise return a stale window on a cache hit- # from an earlier day.- #- # Includes Family#recurring_transaction_merchants_version because the- # cached records are preloaded with :merchant and rendered with its- # name/logo, but editing a FamilyMerchant or a shared ProviderMerchant- # doesn't touch `recurring_transactions`.def projected_recurring_cache_key"transactions_projected_recurring/v6/#{Current.family.id}/#{Current.user.id}/#{Date.current}/" \"#{Current.family.recurring_transactions_version}/#{Current.family.accounts_status_version}/" \"#{Current.family.recurring_transaction_merchants_version}/#{Current.account_share_version}"end- # The "Mark as Recurring" block is only ever rendered under these same- # conditions (see transactions/show.html.erb), so skip the extra query- # entirely when it won't be used — this runs on every show/failed-update- # render, including read-only viewers and split-child transactions.+ def covering_series_for(entry)+ Current.family.recurring_transactions.accessible_by(Current.user).covering(entry)+ end++ def mark_recurring_blocked_message(transaction)+ if covering_series_for(transaction.entry)+ t("recurring_transactions.already_covered")+ elsif RecurringTransaction.identity_taken_by(transaction)+ t("recurring_transactions.already_exists")+ end+ end+def assign_mark_recurring_statereturn unless can_edit_entry? && [email protected]_child?- existing = @entry.transaction.existing_manual_recurring_transaction+ blocked = mark_recurring_blocked_message(@entry.transaction)@mark_recurring_href = mark_as_recurring_transaction_path(@entry.transaction)- @mark_recurring_subtitle_class = existing ? "text-subdued" : "text-secondary"- @mark_recurring_subtitle = existing ? t("recurring_transactions.already_exists") : t("transactions.show.mark_recurring_subtitle")- @mark_recurring_disabled = existing.present?- @mark_recurring_title = existing ? t("recurring_transactions.already_exists") : nil- @mark_recurring_button_class = existing ? "disabled:opacity-50" : nil+ @mark_recurring_subtitle_class = blocked ? "text-subdued" : "text-secondary"+ @mark_recurring_subtitle = blocked || t("transactions.show.mark_recurring_subtitle")+ @mark_recurring_disabled = blocked.present?+ @mark_recurring_title = blocked+ @mark_recurring_button_class = blocked ? "disabled:opacity-50" : nilenddef accessible_transactionsdiff --git a/app/models/recurring_transaction.rb b/app/models/recurring_transaction.rbindex f8ad7130af..db25fd01c3 100644--- a/app/models/recurring_transaction.rb+++ b/app/models/recurring_transaction.rb@@ -145,6 +145,15 @@ class RecurringTransaction < ApplicationRecordname.presence || merchant&.nameend+ # Every name this series answers to, normalised: its own, the name the+ # detector matched on, and the bank texts it has learned. The one place a+ # series' names are compared, so the matcher and the covering check below+ # cannot drift apart.+ def known_names+ ([ name, matcher_name ] + Array(matcher_hints["name_aliases"]))+ .compact.map { |known| RecurringTransaction::Matcher.normalize_name(known) }.to_set+ end+# The name the detector matched on, kept apart from the user-facing name# so renaming a bill does not orphan it from its bank transactions.def matcher_name@@ -546,6 +555,77 @@ class RecurringTransaction < ApplicationRecordcandidate_amount.between?(low, high)end+ # The series in this scope that an entry already belongs to, if any. Guards+ # both ways of turning a transaction into a bill ("Create bill" and "Mark as+ # recurring"), so it sees what the matcher sees: detected series as well as+ # hand-made ones. A declared bill is keyed by name and a detected one by+ # merchant, so the unique indexes never collide between the two.+ #+ # An entry with a confirmed allocation is covered by that series, whatever+ # its identity. Otherwise a non-ended series covers it when it shares the+ # currency and account (an accountless series takes any account), the+ # merchant when the series has one, or else a name the series knows (the+ # entry's own text, or its merchant's name, which is what "Create bill"+ # names a bill after), and an amount inside the variance band, so a second+ # price tier stays creatable. The band is signed, so an inflow never lands+ # inside a bill's band, nor an outflow inside income's. A series the user+ # rejected for this entry ("Not this one") is skipped, as the matcher skips+ # it, so the rejected payment can still become a bill of its own.+ #+ # Identity covers ordinary charges only. The matcher never pays a bill with+ # a transfer leg, and a recurring transfer is keyed by its account pair and+ # has its own "mark as recurring" path, so a transfer leg is covered only+ # through an allocation.+ def self.covering(entry)+ scope = where(family_id: entry.account.family_id).where.not(status: "ended")++ allocated = scope.joins(recurring_occurrences: :allocations)+ .merge(RecurringAllocation.confirmed)+ .find_by(recurring_allocations: { entry_id: entry.id })+ return allocated if allocated+ return if entry.entryable.try(:transfer?)++ merchant = entry.entryable.try(:merchant)+ names = [ entry.name, merchant&.name ].compact_blank.map { |name| Matcher.normalize_name(name) }++ scope.where(currency: entry.currency, account_id: [ entry.account_id, nil ], destination_account_id: nil)+ .where.not(id: RecurringMatchRejection.where(entry_id: entry.id).select(:recurring_transaction_id))+ .order(:created_at)+ .find do |series|+ next false unless amount_within_variance_band?(entry.amount, series.amount)++ if series.merchant_id.present?+ series.merchant_id == merchant&.id+ else+ series.known_names.intersect?(names)+ end+ end+ end++ # The row create_from_transaction would collide with, whatever its status.+ # The partial unique indexes ignore status, so an ended series still holds+ # its key after covering has stopped returning it. Mirrors the identity+ # written below: merchant when the transaction has one (the merchant index+ # ignores name), else the entry's name, with the amount as dedup_scope.+ def self.identity_taken_by(transaction)+ entry = transaction.entry+ key = {+ family_id: entry.account.family_id,+ account_id: entry.account_id,+ destination_account_id: nil,+ amount: entry.amount,+ currency: entry.currency,+ dedup_scope: entry.amount.to_d.to_s("F")+ }+ key = if transaction.merchant_id.present?+ key.merge(merchant_id: transaction.merchant_id)+ else+ key.merge(merchant_id: nil, name: entry.name)+ end++ find_by(key)+ 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)diff --git a/app/models/recurring_transaction/allocator.rb b/app/models/recurring_transaction/allocator.rbindex 38e6e23312..06bb4fd85b 100644--- a/app/models/recurring_transaction/allocator.rb+++ b/app/models/recurring_transaction/allocator.rb@@ -30,6 +30,22 @@ class RecurringTransactionattr_reader :occurrence+ # Takes the entry's advisory lock for the rest of the caller's transaction+ # (it is transaction-scoped, so the caller must have one open). Allocation+ # writes take it, and so does anything that decides from an entry's+ # allocations whether to make a new series for it, so the two serialize.+ def self.lock_entry!(entry)+ RecurringOccurrence.lease_connection.execute(+ ActiveRecord::Base.sanitize_sql_array(+ [ "SELECT pg_advisory_xact_lock(?::int, ?::int)", ENTRY_LOCK_NAMESPACE, entry_lock_id(entry) ]+ )+ )+ end++ def self.entry_lock_id(entry)+ Digest::MD5.hexdigest(entry.id.to_s).to_i(16) % (2**31)+ end+def initialize(occurrence)@occurrence = occurrenceend@@ -184,19 +200,10 @@ class RecurringTransactiondef with_entry_lock(entry)return yield if entry.nil?- occurrence.class.lease_connection.execute(- ActiveRecord::Base.sanitize_sql_array(- [ "SELECT pg_advisory_xact_lock(?::int, ?::int)", ENTRY_LOCK_NAMESPACE, entry_lock_id(entry) ]- )- )-+ self.class.lock_entry!(entry)yieldend- def entry_lock_id(entry)- Digest::MD5.hexdigest(entry.id.to_s).to_i(16) % (2**31)- end-# A confirmed payment pins the obligation it was made against. Open rows# otherwise inherit their amount from the series, which is correct until# money has moved: after that, re-resolving would re-target a payment thediff --git a/app/models/recurring_transaction/declared_bill.rb b/app/models/recurring_transaction/declared_bill.rbindex 2985b658f1..503755b9c2 100644--- a/app/models/recurring_transaction/declared_bill.rb+++ b/app/models/recurring_transaction/declared_bill.rb@@ -116,7 +116,10 @@ class RecurringTransactionreturn falseend- recurring.save+ # Its own savepoint: a caller may hold a transaction open around this+ # (the add-bill form locks the source entry), and a unique violation+ # inside that one would abort it before the rescue below could answer.+ RecurringTransaction.transaction(requires_new: true) { recurring.save }rescue ActiveRecord::RecordNotUniquerecurring.errors.add(:base, I18n.t("recurring_transactions.create.already_exists"))falsediff --git a/app/models/recurring_transaction/matcher.rb b/app/models/recurring_transaction/matcher.rbindex 3c50453f76..80402e8885 100644--- a/app/models/recurring_transaction/matcher.rb+++ b/app/models/recurring_transaction/matcher.rb@@ -375,8 +375,7 @@ class RecurringTransactiondef known_names(series)@known_names ||= {}- @known_names[series.id] ||= ([ series.name, series.matcher_name ] + Array(series.matcher_hints["name_aliases"]))- .compact.map { |name| self.class.normalize_name(name) }.to_set+ @known_names[series.id] ||= series.known_namesenddef normalize_name(name)diff --git a/app/models/transaction.rb b/app/models/transaction.rbindex 55b34b9684..0684885de7 100644--- a/app/models/transaction.rb+++ b/app/models/transaction.rb@@ -393,20 +393,6 @@ class Transaction < ApplicationRecordpotential_posted_match_data.present? && !potential_duplicate_dismissed?end- # Manual recurring transactions are unique per (family, account, merchant/name, amount, currency)- # — see the partial unique indexes on recurring_transactions. Used to guard "mark as recurring"- # so the UI can disable the action ahead of time instead of failing after a POST.- def existing_manual_recurring_transaction- entry.account.family.recurring_transactions.find_by(- account_id: entry.account_id,- merchant_id: merchant_id,- name: merchant_id.present? ? nil : entry.name,- amount: entry.amount,- currency: entry.currency,- manual: true- )- end-def potential_duplicate_entryreturn nil unless has_potential_duplicate?Entry.find_by(id: potential_posted_match_data["entry_id"])diff --git a/app/views/recurring_transactions/_form.html.erb b/app/views/recurring_transactions/_form.html.erbindex 18451f7dc2..7c8979e43d 100644--- a/app/views/recurring_transactions/_form.html.erb+++ b/app/views/recurring_transactions/_form.html.erb@@ -1,4 +1,4 @@-<%# locals: (recurring_transaction:, sibling_count: 0) %>+<%# locals: (recurring_transaction:, sibling_count: 0, source_entry_id: nil, allow_duplicate: false) %><%# Income mode reshapes the dialog: a paycheck has a source and a payday,not a biller portal and an autopay toggle. %>@@ -76,6 +76,14 @@<%= hidden_field_tag "recurring_transaction[is_income]", "1" %><% end %>+ <%# The transaction a prefilled dialog came from travels with the form, so+ create can ask it whether a bill already covers it: the fields alone+ carry a name, and a detected bill is keyed by merchant. %>+ <% if recurring_transaction.new_record? && source_entry_id %>+ <%= hidden_field_tag :entry_id, source_entry_id, id: nil %>+ <%= hidden_field_tag :allow_duplicate, "1", id: nil if allow_duplicate %>+ <% end %>+<%# Name, amount, due date and how often are the whole job for mostbills. How often used to render below the payment link and theautopay toggle, so the fourth thing anyone needs sat under twodiff --git a/app/views/recurring_transactions/new.html.erb b/app/views/recurring_transactions/new.html.erbindex f622ed2f3d..049c8fb691 100644--- a/app/views/recurring_transactions/new.html.erb+++ b/app/views/recurring_transactions/new.html.erb@@ -72,6 +72,52 @@</div><% end %>- <%= render "form", recurring_transaction: @recurring_transaction, sibling_count: 0 %>+ <% if @covering_series %>+ <%# The transaction this dialog was opened from is already paying a bill.+ Saving would count it twice, so the bill comes first and the form+ waits behind a deliberate choice: a second price tier is the one+ legitimate reason to want another. %>+ <%# A suggestion is that bill, found by detection and not yet confirmed.+ Confirming it links this payment; a separate bill would become the+ duplicate the moment the suggestion was confirmed. %>+ <%# Income is stored negative, so an inflow's covering series is income+ and the warning names it as such. %>+ <% suggested = @covering_series.suggested? %>+ <% covered = @covering_series.amount.negative? ? ".covered_income" : ".covered" %>+ <div class="mb-5">+ <%= render DS::Alert.new(title: t(suggested ? "#{covered}_suggested_title" : "#{covered}_title"), variant: :warning, live: :polite) do %>+ <p><%= t(suggested ? "#{covered}_suggested_body" : "#{covered}_body", name: @covering_series.display_name) %></p>+ <div class="flex flex-wrap items-center gap-3">+ <% if suggested && series_writable?(@covering_series) %>+ <%= render DS::Link.new(+ text: t("#{covered}_confirm"),+ variant: "primary",+ href: confirm_recurring_transaction_path(@covering_series),+ method: :post,+ frame: "_top"+ ) %>+ <% end %>+ <%= render DS::Link.new(+ text: t("#{covered}_open"),+ variant: :default,+ href: bill_path(@covering_series),+ frame: "_top"+ ) %>+ </div>+ <% end %>+ </div>++ <%= render DS::Disclosure.new(title: t("#{covered}_create_anyway"), align: "left") do %>+ <div class="pt-2">+ <%= render "form", recurring_transaction: @recurring_transaction, sibling_count: 0,+ source_entry_id: @source_entry&.id, allow_duplicate: true %>+ </div>+ <% end %>+ <% else %>+ <%# A failed save after "anyway" keeps that choice for the resubmit. %>+ <%= render "form", recurring_transaction: @recurring_transaction, sibling_count: 0,+ source_entry_id: @source_entry&.id,+ allow_duplicate: separate_bill_chosen? %>+ <% end %><% end %><% end %>diff --git a/config/locales/views/recurring_transactions/en.yml b/config/locales/views/recurring_transactions/en.ymlindex 6f87367387..645940e89a 100644--- a/config/locales/views/recurring_transactions/en.yml+++ b/config/locales/views/recurring_transactions/en.yml@@ -63,6 +63,20 @@ en:pick_different: Start from a different transactionsmart_fill: Smart-fill with AIsmart_fill_applied: AI suggested these values from the charge history. Review before saving.+ covered_title: This transaction already belongs to a bill+ covered_body: "%{name} already tracks this payment, so a new bill would count it twice."+ covered_open: Open bill+ covered_suggested_title: Sure already suggested a bill for this payment+ covered_suggested_body: "%{name} is waiting in your suggestions. Confirm it to start tracking it, so a new bill does not count this payment twice. Matching payments are linked automatically, and you can link this one from the bill."+ covered_confirm: Confirm bill+ covered_create_anyway: Create a separate bill anyway+ covered_income_title: This deposit already belongs to an income+ covered_income_body: "%{name} already tracks this deposit, so adding it again would count it twice."+ covered_income_open: Open income+ covered_income_suggested_title: Sure already suggested this income+ covered_income_suggested_body: "%{name} is waiting in your suggestions. Add it to start tracking it, so this deposit is not counted twice. Matching deposits are linked automatically, and you can link this one from the income."+ covered_income_confirm: Add income+ covered_income_create_anyway: Add a separate income anywaysmart_fills:create:failed: Could not analyze the charge history right now. The form kept the transaction's own values.@@ -169,6 +183,7 @@ en:confirm_delete_income: "Remove %{name} as income? Your transactions stay exactly as they are. This only removes the income and its schedule."marked_as_recurring: Transaction marked as recurringalready_exists: A manual recurring transaction already exists for this pattern+ already_covered: This transaction already matches a recurring transactioncreation_failed: Failed to create recurring transaction. Please check the transaction details and try again.unexpected_error: An unexpected error occurred while creating the recurring transactionamount_range: "Range: %{min} to %{max}"diff --git a/test/controllers/recurring_transactions/smart_fills_controller_test.rb b/test/controllers/recurring_transactions/smart_fills_controller_test.rbindex b474871d61..aa40308188 100644--- a/test/controllers/recurring_transactions/smart_fills_controller_test.rb+++ b/test/controllers/recurring_transactions/smart_fills_controller_test.rb@@ -78,6 +78,23 @@ class RecurringTransactions::SmartFillsControllerTest < ActionDispatch::Integratassert_no_match "Should not appear", response.bodyend+ test "smart fill on a transaction a bill already covers still warns" do+ detected = @family.recurring_transactions.create!(+ account: accounts(:depository), name: "GYM MEMBERSHIP", amount: 40, currency: "USD",+ expected_day_of_month: Date.current.day, last_occurrence_date: 1.month.ago.to_date,+ next_expected_date: Date.current, status: "active", manual: false, occurrence_count: 2+ )+ stub_provider(raw(name: "Gym Membership", amount: 40.0, frequency: "monthly", confidence: 0.9))++ post smart_fill_recurring_transactions_url(entry_id: @entry.id),+ headers: { "Turbo-Frame" => "modal" }++ assert_response :success+ assert_match I18n.t("recurring_transactions.new.covered_title"), response.body+ assert_select "a[href=?]", bill_path(detected)+ assert_select "input[type=hidden][name=entry_id][value=?]", @entry.id+ end+privatedef raw(**overrides)diff --git a/test/controllers/recurring_transactions_controller_test.rb b/test/controllers/recurring_transactions_controller_test.rbindex d2ab1be984..ce2d1f474c 100644--- a/test/controllers/recurring_transactions_controller_test.rb+++ b/test/controllers/recurring_transactions_controller_test.rb@@ -1461,8 +1461,300 @@ class RecurringTransactionsControllerTest < ActionDispatch::IntegrationTestassert_equal "https://pay.example/theirs", read_only_sibling.reload.payment_urlend+ # "Create bill" from a transaction used to save a second bill for a payment+ # that was already paying one (#4368): the declared bill is keyed by name,+ # the detected one by merchant, so no unique index could ever collide.+ test "new from a transaction a bill already covers names that bill and links to it" do+ entry, detected = covered_entry_and_detected_bill++ get new_recurring_transaction_url(entry_id: entry.id), headers: { "Turbo-Frame" => "modal" }++ assert_response :success+ assert_match I18n.t("recurring_transactions.new.covered_title"), response.body+ assert_select "a[href=?]", bill_path(detected), text: I18n.t("recurring_transactions.new.covered_open")+ assert_select "input[type=hidden][name=entry_id][value=?]", entry.id+ assert_select "input[type=hidden][name=allow_duplicate][value=1]"+ assert_select "a[href=?]", confirm_recurring_transaction_path(detected), count: 0+ end++ # An inflow is covered by a recurring income, not a bill, and the dialog+ # around it is already the income one, so the warning speaks of income too.+ test "new from a deposit a recurring income covers speaks of income" do+ entry = accounts(:depository).entries.create!(+ date: Date.current, amount: -1840, currency: "USD", name: "ACME PAYROLL",+ entryable: Transaction.new(merchant: covering_merchant)+ )+ income = @family.recurring_transactions.create!(+ account: accounts(:depository), merchant: covering_merchant, name: nil, bill_type: "income",+ amount: -1840, currency: "USD", expected_day_of_month: Date.current.day,+ last_occurrence_date: 1.month.ago.to_date, next_expected_date: Date.current,+ status: "active", manual: false, occurrence_count: 2+ )++ { "active" => %w[covered_income_title covered_title], "suggested" => %w[covered_income_suggested_title covered_suggested_title] }.each do |status, (income_title, bill_title)|+ income.update!(status: status)++ get new_recurring_transaction_url(entry_id: entry.id), headers: { "Turbo-Frame" => "modal" }++ assert_response :success+ assert_match I18n.t("recurring_transactions.new.#{income_title}"), response.body+ assert_no_match I18n.t("recurring_transactions.new.#{bill_title}"), response.body+ assert_select "a[href=?]", bill_path(income), text: I18n.t("recurring_transactions.new.covered_income_open")+ assert_match I18n.t("recurring_transactions.new.covered_income_create_anyway"), response.body+ end+ assert_select "a[href=?]", confirm_recurring_transaction_path(income), text: I18n.t("recurring_transactions.new.covered_income_confirm")+ end++ # A suggestion is a bill Sure found and is waiting on. Saving a separate one+ # now would only become a duplicate when the suggestion is confirmed, so the+ # dialog offers the confirm instead, with the separate bill still behind it.+ test "new from a transaction a suggested bill covers offers to confirm it" do+ entry, suggested = covered_entry_and_detected_bill(status: "suggested")++ get new_recurring_transaction_url(entry_id: entry.id), headers: { "Turbo-Frame" => "modal" }++ assert_response :success+ assert_match I18n.t("recurring_transactions.new.covered_suggested_title"), response.body+ assert_no_match I18n.t("recurring_transactions.new.covered_title"), response.body+ # Confirming links payments within the bill's tolerance, not necessarily+ # this one: covering accepts 0.5x to 2x. The copy must not promise it.+ assert_select "p", text: I18n.t("recurring_transactions.new.covered_suggested_body", name: suggested.display_name)+ assert_no_match "track this payment", response.body+ assert_select "a[href=?][data-turbo-method=post][data-turbo-frame=_top]",+ confirm_recurring_transaction_path(suggested),+ text: I18n.t("recurring_transactions.new.covered_confirm")+ assert_select "a[href=?]", bill_path(suggested), text: I18n.t("recurring_transactions.new.covered_open")+ assert_select "input[type=hidden][name=allow_duplicate][value=1]"+ end++ # The confirm action 404s for a read-only share, so the dialog must not+ # offer a button that can only fail.+ test "a read-only share is told about the suggestion but not offered the confirm" do+ member = users(:family_member)+ member.update!(preferences: (member.preferences || {}).merge("preview_features_enabled" => true))+ # The credit card fixture is shared with the member read_only.+ entry, suggested = covered_entry_and_detected_bill(status: "suggested", account: accounts(:credit_card))++ sign_in member+ get new_recurring_transaction_url(entry_id: entry.id), headers: { "Turbo-Frame" => "modal" }++ assert_response :success+ assert_match I18n.t("recurring_transactions.new.covered_suggested_title"), response.body+ assert_select "a[href=?]", confirm_recurring_transaction_path(suggested), count: 0+ assert_select "a[href=?]", bill_path(suggested)+ end++ test "new from a transaction no bill covers shows no warning" do+ entry = accounts(:depository).entries.create!(+ date: Date.current, amount: 100, currency: "USD", name: "FRESH CHARGE",+ entryable: Transaction.new(merchant: covering_merchant)+ )++ get new_recurring_transaction_url(entry_id: entry.id), headers: { "Turbo-Frame" => "modal" }++ assert_response :success+ assert_no_match I18n.t("recurring_transactions.new.covered_title"), response.body+ assert_select "input[type=hidden][name=entry_id][value=?]", entry.id+ assert_select "input[name=allow_duplicate]", count: 0+ end++ # The submitted fields carry only a name; the detected bill has a merchant+ # and no name. Identity has to come from the posted entry, or this passes.+ test "create refuses a second bill for a transaction a merchant-keyed bill covers" do+ entry, detected = covered_entry_and_detected_bill++ assert_no_difference "RecurringTransaction.count" do+ post recurring_transactions_url, params: covered_create_params(entry)+ end++ assert_response :unprocessable_entity+ assert_match I18n.t("recurring_transactions.new.covered_title"), response.body+ assert_select "a[href=?]", bill_path(detected)+ end++ test "create makes the separate bill when asked to" do+ entry, = covered_entry_and_detected_bill++ assert_difference "RecurringTransaction.count", 1 do+ post recurring_transactions_url, params: covered_create_params(entry).merge(allow_duplicate: "1")+ end++ assert_redirected_to bills_path+ end++ # The dialog only ever posts "1". Anything else, such as the "0" or "false"+ # a direct POST might send, is not the separate-bill choice.+ test "create refuses a covered transaction when allow_duplicate is anything but 1" do+ entry, = covered_entry_and_detected_bill++ [ "0", "false" ].each do |value|+ assert_no_difference "RecurringTransaction.count", "allow_duplicate=#{value} skipped the check" do+ post recurring_transactions_url, params: covered_create_params(entry).merge(allow_duplicate: value)+ end++ assert_response :unprocessable_entity+ assert_match I18n.t("recurring_transactions.new.covered_title"), response.body+ end+ end++ test "a failed create does not turn another allow_duplicate value into the choice" do+ entry = accounts(:depository).entries.create!(+ date: Date.current, amount: 100, currency: "USD", name: "FRESH CHARGE",+ entryable: Transaction.new(merchant: covering_merchant)+ )+ params = covered_create_params(entry).merge(allow_duplicate: "0")+ params[:recurring_transaction][:first_due_on] = ""++ post recurring_transactions_url, params: params++ assert_response :unprocessable_entity+ assert_select "input[type=hidden][name=entry_id][value=?]", entry.id+ assert_select "input[name=allow_duplicate]", count: 0+ end++ test "create from a transaction no bill covers still saves" do+ entry = accounts(:depository).entries.create!(+ date: Date.current, amount: 100, currency: "USD", name: "FRESH CHARGE",+ entryable: Transaction.new(merchant: covering_merchant)+ )++ assert_difference "RecurringTransaction.count", 1 do+ post recurring_transactions_url, params: covered_create_params(entry)+ end++ assert_redirected_to bills_path+ end++ # "Create a separate bill anyway" is a choice the user already made. A+ # validation error on that submission must not drop it, or fixing the error+ # and resubmitting is refused again behind the warning.+ test "a failed create keeps the separate-bill choice on the re-render" do+ entry, = covered_entry_and_detected_bill+ params = covered_create_params(entry).merge(allow_duplicate: "1")+ params[:recurring_transaction][:first_due_on] = ""++ assert_no_difference "RecurringTransaction.count" do+ post recurring_transactions_url, params: params+ end++ assert_response :unprocessable_entity+ assert_match ERB::Util.html_escape(I18n.t("recurring_transactions.create.due_date_required")), response.body+ assert_select "input[type=hidden][name=entry_id][value=?]", entry.id+ assert_select "input[type=hidden][name=allow_duplicate][value=1]"+ end++ test "a failed create that never chose a separate bill does not gain the choice" do+ entry = accounts(:depository).entries.create!(+ date: Date.current, amount: 100, currency: "USD", name: "FRESH CHARGE",+ entryable: Transaction.new(merchant: covering_merchant)+ )+ params = covered_create_params(entry)+ params[:recurring_transaction][:first_due_on] = ""++ post recurring_transactions_url, params: params++ assert_response :unprocessable_entity+ assert_select "input[type=hidden][name=entry_id][value=?]", entry.id+ assert_select "input[name=allow_duplicate]", count: 0+ end++ # Two submissions from the same transaction could both see no covering bill+ # and both save, and so could a submission racing an allocation of that+ # transaction or a "Mark as recurring" on it. The check and the save hold+ # the entry lock the Allocator takes, so each waits for the other.+ test "create checks for a covering bill and saves while holding the entry lock" do+ entry = accounts(:depository).entries.create!(+ date: Date.current, amount: 100, currency: "USD", name: "FRESH CHARGE",+ entryable: Transaction.new(merchant: covering_merchant)+ )+ connection = ActiveRecord::Base.connection+ outside = connection.open_transactions+ seen = {}++ RecurringTransactionsController.any_instance.stubs(:covering_series_for)+ .with { seen[:check] = [ connection.open_transactions, entry_lock_held?(entry) ]; true }.returns(nil)+ RecurringTransaction::DeclaredBill.stubs(:save)+ .with { seen[:save] = [ connection.open_transactions, entry_lock_held?(entry) ]; true }.returns(true)+ assert_not entry_lock_held?(entry), "precondition: nothing holds the entry lock before the request"++ post recurring_transactions_url, params: covered_create_params(entry)++ assert_redirected_to bills_path+ assert_operator seen[:check].first, :>, outside, "the covering check ran outside a transaction"+ assert_operator seen[:save].first, :>, outside, "the save ran outside a transaction"+ assert seen[:check].last, "the covering check ran without the entry lock"+ assert seen[:save].last, "the save ran without the entry lock"+ end++ # The save now runs inside the lock's transaction, so a unique-index+ # collision must still come back as a 422, not abort that transaction.+ test "create under the lock still reports an existing bill with the same identity" do+ entry = accounts(:depository).entries.create!(+ date: Date.current, amount: 100, currency: "USD", name: "FRESH CHARGE",+ entryable: Transaction.new(merchant: covering_merchant)+ )+ @family.recurring_transactions.create!(+ account: accounts(:depository), name: "Household Plan", amount: 100, currency: "USD",+ dedup_scope: BigDecimal("100").to_s("F"), expected_day_of_month: Date.current.day,+ last_occurrence_date: 1.month.ago.to_date, next_expected_date: Date.current,+ status: "active", manual: true, occurrence_count: 0+ )+ params = covered_create_params(entry)+ params[:recurring_transaction][:name] = "Household Plan"++ assert_no_difference "RecurringTransaction.count" do+ post recurring_transactions_url, params: params+ end++ assert_response :unprocessable_entity+ assert_match I18n.t("recurring_transactions.create.already_exists"), response.body+ end+private+ # The Allocator's two-key advisory lock on this entry, held by this session.+ def entry_lock_held?(entry)+ ActiveRecord::Base.connection.select_value(ActiveRecord::Base.sanitize_sql_array([ <<~SQL, RecurringTransaction::Allocator::ENTRY_LOCK_NAMESPACE, RecurringTransaction::Allocator.entry_lock_id(entry) ]))+ SELECT EXISTS (+ SELECT 1 FROM pg_locks+ WHERE locktype = 'advisory' AND pid = pg_backend_pid() AND granted+ AND classid = ? AND objid = ? AND objsubid = 2+ )+ SQL+ end++ def covering_merchant+ @covering_merchant ||= @family.merchants.create!(name: "Betashares")+ end++ def covered_entry_and_detected_bill(status: "active", account: accounts(:depository))+ entry = account.entries.create!(+ date: Date.current, amount: 100, currency: account.currency, name: "BETASHARES DIRECT DEBIT",+ entryable: Transaction.new(merchant: covering_merchant)+ )+ detected = @family.recurring_transactions.create!(+ account: account, merchant: covering_merchant, name: nil,+ amount: 100, currency: account.currency, expected_day_of_month: Date.current.day,+ last_occurrence_date: 1.month.ago.to_date, next_expected_date: Date.current,+ status: status, manual: false, occurrence_count: 2+ )+ [ entry, detected ]+ end++ # What the prefilled dialog posts: the merchant's name, never its id.+ def covered_create_params(entry)+ {+ entry_id: entry.id,+ recurring_transaction: {+ name: "Betashares",+ amount: "100",+ account_id: accounts(:depository).id,+ first_due_on: (Date.current + 1.month).iso8601,+ frequency_preset: "monthly"+ }+ }+ end+def create_series(name:, account: accounts(:depository), merchant: nil, status: "active", payment_url: nil,amount: 25, bill_type: "bill")@family.recurring_transactions.create!(diff --git a/test/controllers/transactions_controller_test.rb b/test/controllers/transactions_controller_test.rbindex 0cf8987d8e..7f051a5701 100644--- a/test/controllers/transactions_controller_test.rb+++ b/test/controllers/transactions_controller_test.rb@@ -412,7 +412,7 @@ class TransactionsControllerTest < ActionDispatch::IntegrationTest}assert_response :unprocessable_entity- assert_includes response.body, "A manual recurring transaction already exists for this pattern"+ assert_includes response.body, I18n.t("recurring_transactions.already_covered")assert_select "button[disabled]", text: /Mark as Recurring/end@@ -897,7 +897,7 @@ endendassert_redirected_to transactions_path- assert_equal "A manual recurring transaction already exists for this pattern", flash[:alert]+ assert_equal I18n.t("recurring_transactions.already_covered"), flash[:alert]endtest "mark_as_recurring allows a second manual recurring transaction with same merchant but different amount" do@@ -984,7 +984,139 @@ endendassert_redirected_to transactions_path- assert_equal "A manual recurring transaction already exists for this pattern", flash[:alert]+ assert_equal I18n.t("recurring_transactions.already_covered"), flash[:alert]+ end++ # Only hand-made rows used to count, so a bill that detection had already+ # found never disabled the button (#4368).+ test "mark_as_recurring refuses a transaction a detected bill already covers" do+ family = families(:empty)+ sign_in users(:empty)+ account = family.accounts.create! name: "Test", balance: 0, currency: "USD", accountable: Depository.new+ merchant = family.merchants.create! name: "Betashares"+ entry = create_transaction(account: account, amount: 100, merchant: merchant)++ family.recurring_transactions.create!(+ account: account,+ merchant: merchant,+ amount: 100,+ currency: entry.currency,+ expected_day_of_month: entry.date.day,+ last_occurrence_date: entry.date,+ next_expected_date: 1.month.from_now,+ status: "active",+ manual: false,+ occurrence_count: 2+ )++ get transaction_url(entry)+ assert_select "button[disabled][title=?]", I18n.t("recurring_transactions.already_covered"), text: /Mark as Recurring/+ assert_select "##{ActionView::RecordIdentifier.dom_id(entry, :mark_recurring)} p",+ text: I18n.t("recurring_transactions.already_covered")++ assert_no_difference "RecurringTransaction.count" do+ post mark_as_recurring_transaction_path(entry.entryable)+ end++ assert_redirected_to transactions_path+ assert_equal I18n.t("recurring_transactions.already_covered"), flash[:alert]+ end++ # The covering series may be income, or only a suggestion, so the message+ # must not tell the user a bill is tracking the payment.+ test "mark_as_recurring does not call a suggested income a bill" do+ family = families(:empty)+ sign_in users(:empty)+ account = family.accounts.create! name: "Test", balance: 0, currency: "USD", accountable: Depository.new+ merchant = family.merchants.create! name: "Acme Payroll"+ entry = create_transaction(account: account, amount: -1840, merchant: merchant)+ family.recurring_transactions.create!(+ account: account, merchant: merchant, amount: -1840, currency: "USD", bill_type: "income",+ expected_day_of_month: entry.date.day, last_occurrence_date: entry.date,+ next_expected_date: 1.month.from_now, status: "suggested", manual: false, occurrence_count: 2+ )++ get transaction_url(entry)+ disabled = css_select("button[disabled]").find { |button| button.text.include?("Mark as Recurring") }+ assert disabled, "the covering income must disable the button"+ assert_no_match(/\bbill\b/i, disabled["title"])++ post mark_as_recurring_transaction_path(entry.entryable)+ assert_equal I18n.t("recurring_transactions.already_covered"), flash[:alert]+ assert_no_match(/\bbill\b/i, flash[:alert])+ end++ # An ended series no longer covers the payment, but the unique index still+ # holds its key, so the create would fail. The button says so up front+ # instead of failing after the POST.+ test "mark_as_recurring is disabled when an ended series holds the same key" do+ family = families(:empty)+ sign_in users(:empty)+ account = family.accounts.create! name: "Test", balance: 0, currency: "USD", accountable: Depository.new+ merchant = family.merchants.create! name: "Betashares"+ entry = create_transaction(account: account, amount: 100, merchant: merchant)+ RecurringTransaction.create_from_transaction(entry.entryable).update!(status: "ended")++ get transaction_url(entry)+ assert_select "button[disabled][title=?]", I18n.t("recurring_transactions.already_exists"), text: /Mark as Recurring/++ assert_no_difference "RecurringTransaction.count" do+ post mark_as_recurring_transaction_path(entry.entryable)+ end+ assert_equal I18n.t("recurring_transactions.already_exists"), flash[:alert]+ end++ # Sharing is per account. A bill on an account this member was never given+ # is not theirs to learn about, as in the add-bill dialog's own check, so+ # it neither disables the button nor refuses the request.+ test "mark_as_recurring ignores a covering bill on an account the user cannot see" do+ member = users(:family_member)+ entry = create_transaction(account: accounts(:depository), amount: 100, name: "PRIVATE PLAN")+ hidden = families(:dylan_family).recurring_transactions.create!(+ account: accounts(:investment), name: "Private Plan", amount: 100, currency: "USD",+ expected_day_of_month: Date.current.day, last_occurrence_date: 1.month.ago.to_date,+ next_expected_date: Date.current, status: "active", manual: true, occurrence_count: 1+ )+ hidden.recurring_occurrences.order(:due_on).first.allocations.create!(+ entry: entry, allocated_amount: 100, currency: "USD", source: "user_created"+ )+ assert_equal hidden, families(:dylan_family).recurring_transactions.covering(entry), "precondition: the hidden bill covers the entry"++ sign_in member+ get transaction_url(entry)+ assert_select "button[disabled]", text: /Mark as Recurring/, count: 0++ assert_difference "RecurringTransaction.count", 1 do+ post mark_as_recurring_transaction_path(entry.entryable)+ end+ assert_equal I18n.t("recurring_transactions.marked_as_recurring"), flash[:notice]+ end++ # The add-bill form checks and saves under the entry lock the Allocator+ # takes. This path makes a series for the same transaction, so it holds the+ # same lock, or the two could both see nothing and both create.+ test "mark_as_recurring checks and creates while holding the entry lock" do+ family = families(:empty)+ sign_in users(:empty)+ account = family.accounts.create! name: "Test", balance: 0, currency: "USD", accountable: Depository.new+ entry = create_transaction(account: account, amount: 100, name: "FRESH CHARGE")+ connection = ActiveRecord::Base.connection+ outside = connection.open_transactions+ seen = {}++ TransactionsController.any_instance.stubs(:mark_recurring_blocked_message)+ .with { seen[:check] = [ connection.open_transactions, entry_lock_held?(entry) ]; true }.returns(nil)+ RecurringTransaction.stubs(:create_from_transaction)+ .with { seen[:create] = [ connection.open_transactions, entry_lock_held?(entry) ]; true }.returns(true)+ assert_not entry_lock_held?(entry), "precondition: nothing holds the entry lock before the request"++ post mark_as_recurring_transaction_path(entry.entryable)++ assert_equal I18n.t("recurring_transactions.marked_as_recurring"), flash[:notice]+ assert_operator seen[:check].first, :>, outside, "the check ran outside a transaction"+ assert_operator seen[:create].first, :>, outside, "the create ran outside a transaction"+ assert seen[:check].last, "the check ran without the entry lock"+ assert seen[:create].last, "the create ran without the entry lock"endtest "mark_as_recurring shows already-exists alert when a concurrent request wins the race" do@@ -1975,6 +2107,17 @@ endendprivate+ # The Allocator's two-key advisory lock on this entry, held by this session.+ def entry_lock_held?(entry)+ ActiveRecord::Base.connection.select_value(ActiveRecord::Base.sanitize_sql_array([ <<~SQL, RecurringTransaction::Allocator::ENTRY_LOCK_NAMESPACE, RecurringTransaction::Allocator.entry_lock_id(entry) ]))+ SELECT EXISTS (+ SELECT 1 FROM pg_locks+ WHERE locktype = 'advisory' AND pid = pg_backend_pid() AND granted+ AND classid = ? AND objid = ? AND objsubid = 2+ )+ SQL+ end+def rendered_entry_idscss_select("turbo-frame[id^='entry_']").map { |node| node["id"].delete_prefix("entry_") }enddiff --git a/test/models/recurring_transaction_test.rb b/test/models/recurring_transaction_test.rbindex 4105f7ac65..88e81c6e4a 100644--- a/test/models/recurring_transaction_test.rb+++ b/test/models/recurring_transaction_test.rb@@ -1,6 +1,8 @@require "test_helper"class RecurringTransactionTest < ActiveSupport::TestCase+ include EntriesTestHelper+def setup@family = families(:dylan_family)@merchant = merchants(:netflix)@@ -633,6 +635,243 @@ class RecurringTransactionTest < ActiveSupport::TestCaseassert_not RecurringTransaction.amount_within_variance_band?(-10, 100)end+ # The check behind "Create bill" and "Mark as recurring" on a transaction:+ # is there already a bill this payment belongs to? It has to see detected+ # bills as well as hand-made ones. A declared bill is keyed by name and a+ # detected one by merchant, so no unique index collides between the two.+ test "covering finds a detected merchant-keyed bill" do+ setup_covering_family+ entry = create_transaction(account: @account, amount: 100, merchant: @merchant, name: "BETASHARES DIRECT DEBIT")+ detected = covering_series(merchant: @merchant, amount: 100, manual: false)++ assert_equal detected, @family.recurring_transactions.covering(entry)+ end++ test "covering finds a hand-made bill keyed by name" do+ setup_covering_family+ entry = create_transaction(account: @account, amount: 50, name: "Netflix")+ declared = covering_series(name: "Netflix", amount: 50)++ assert_equal declared, @family.recurring_transactions.covering(entry)+ end++ # "Create bill" names the bill after the merchant, not the bank's text, so a+ # declared bill made that way has to be found from the merchant's name.+ test "covering finds a declared bill named after the entry's merchant" do+ setup_covering_family+ entry = create_transaction(account: @account, amount: 100, merchant: @merchant, name: "BETASHARES DIRECT DEBIT 123")+ declared = covering_series(name: " betashares ", amount: 100)++ assert_equal declared, @family.recurring_transactions.covering(entry)+ end++ test "covering finds a bill through a learned name alias" do+ setup_covering_family+ entry = create_transaction(account: @account, amount: 75, name: "FNB App Payment To Golf Cart")+ renamed = covering_series(name: "GOLF CART", amount: 75)+ renamed.update!(matcher_hints: { "name_aliases" => [ "FNB APP PAYMENT TO GOLF CART" ] })++ assert_equal renamed, @family.recurring_transactions.covering(entry)+ end++ # A rename keeps the bank text as the detected name, so the bill still+ # covers the transaction it was made from.+ test "covering finds a renamed bill through its detected name" do+ setup_covering_family+ entry = create_transaction(account: @account, amount: 40, name: "CITY WATER 0042")+ bill = covering_series(name: "CITY WATER 0042", amount: 40)+ bill.update!(name: "Water")+ assert_equal "CITY WATER 0042", bill.reload.matcher_hints["detected_name"], "precondition: the rename kept the detected name"++ assert_equal bill, @family.recurring_transactions.covering(entry)+ end++ test "covering finds an accountless bill from any account" do+ setup_covering_family+ entry = create_transaction(account: @account, amount: 100, merchant: @merchant)+ accountless = covering_series(merchant: @merchant, amount: 100, account: nil)++ assert_equal accountless, @family.recurring_transactions.covering(entry)+ end++ # The payment is already paying a bill whose identity it does not share+ # (a renamed bill, a payment linked by hand), so only the allocation says so.+ test "covering finds the bill an entry is already allocated to" do+ setup_covering_family+ entry = create_transaction(account: @account, amount: 1200, name: "TRANSFER 4471")+ rent = covering_series(name: "Rent", amount: 1200, manual: false)+ rent.recurring_occurrences.order(:due_on).first.allocations.create!(+ entry: entry, allocated_amount: 1200, currency: "USD", source: "user_created"+ )++ assert_equal rent, @family.recurring_transactions.covering(entry)+ end++ # Both edges of the shared variance band: inclusive at 2x and at half, so a+ # second price tier from one biller (outside it) stays creatable.+ test "covering treats the variance band as inclusive at both edges" do+ setup_covering_family+ covering_series(merchant: @merchant, amount: 100, manual: false)++ covered = [ 50, 150, 200 ].map { |amount| create_transaction(account: @account, amount: amount, merchant: @merchant) }+ uncovered = [ 49.99, 201 ].map { |amount| create_transaction(account: @account, amount: amount, merchant: @merchant) }++ covered.each { |entry| assert_not_nil @family.recurring_transactions.covering(entry), "#{entry.amount} is inside the band" }+ uncovered.each { |entry| assert_nil @family.recurring_transactions.covering(entry), "#{entry.amount} is a different price tier" }+ end++ test "covering ignores a bill on another account" do+ setup_covering_family+ other_account = @family.accounts.create! name: "Other", balance: 0, currency: "USD", accountable: Depository.new+ entry = create_transaction(account: @account, amount: 100, merchant: @merchant)+ covering_series(merchant: @merchant, amount: 100, account: other_account)++ assert_nil @family.recurring_transactions.covering(entry)+ end++ test "covering ignores a bill for another merchant" do+ setup_covering_family+ entry = create_transaction(account: @account, amount: 100, merchant: @merchant, name: "Betashares")+ covering_series(merchant: @family.merchants.create!(name: "Other Merchant"), amount: 100)++ assert_nil @family.recurring_transactions.covering(entry)+ end++ test "covering ignores a bill in another currency" do+ setup_covering_family+ entry = create_transaction(account: @account, amount: 100, merchant: @merchant)+ covering_series(merchant: @merchant, amount: 100, currency: "EUR")++ assert_nil @family.recurring_transactions.covering(entry)+ end++ test "covering ignores a series of the opposite sign" do+ setup_covering_family+ outflow = create_transaction(account: @account, amount: 100, merchant: @merchant)+ inflow = create_transaction(account: @account, amount: -100, merchant: @merchant)+ covering_series(merchant: @merchant, amount: -100, dedup_scope: "income")++ assert_nil @family.recurring_transactions.covering(outflow)+ assert_not_nil @family.recurring_transactions.covering(inflow)+ end++ test "covering ignores an ended bill" do+ setup_covering_family+ entry = create_transaction(account: @account, amount: 100, merchant: @merchant)+ covering_series(merchant: @merchant, amount: 100, status: "ended")++ assert_nil @family.recurring_transactions.covering(entry)+ end++ # "Not this one" on a suggested match records the pair so the matcher never+ # proposes it again. The same answer has to free the payment here, or it+ # could never become a bill of its own. The rejection names one payment, so+ # the bill still covers the next one.+ test "covering skips a bill the user rejected for this payment" do+ setup_covering_family+ entry = create_transaction(account: @account, amount: 100, merchant: @merchant)+ next_payment = create_transaction(account: @account, amount: 100, merchant: @merchant)+ rejected = covering_series(merchant: @merchant, amount: 100, manual: false, status: "suggested")+ assert_equal rejected, @family.recurring_transactions.covering(entry), "precondition: the bill covers the payment before the rejection"++ RecurringMatchRejection.create!(recurring_transaction: rejected, entry: entry)++ assert_nil @family.recurring_transactions.covering(entry)+ assert_equal rejected, @family.recurring_transactions.covering(next_payment)+ end++ # A merchant-keyed bill matches on the merchant, as the matcher does: a+ # merchant-less charge that only shares the text is not its payment.+ test "covering does not match a merchant-keyed bill on name alone" do+ setup_covering_family+ covering_series(merchant: @merchant, amount: 100)+ entry = create_transaction(account: @account, amount: 100, name: "Betashares")++ assert_nil @family.recurring_transactions.covering(entry)+ end++ # An accountless series passes the account filter from any family, so the+ # family pin is what keeps another family's bill out even when unscoped.+ test "covering never returns another family's bill" do+ setup_covering_family+ entry = create_transaction(account: @account, amount: 50, name: "Netflix")+ families(:dylan_family).recurring_transactions.create!(+ account: nil, name: "Netflix", amount: 50, currency: "USD",+ expected_day_of_month: Date.current.day, last_occurrence_date: 1.month.ago.to_date,+ next_expected_date: Date.current, status: "active", manual: true, occurrence_count: 1+ )++ assert_nil RecurringTransaction.covering(entry)+ end++ # The unique indexes ignore status, so a series create_from_transaction+ # would collide with is found whatever state it is in, even when covering+ # (which skips ended series) does not see it. Built from a real create, so+ # the lookup and the index cannot disagree on the key.+ test "identity_taken_by finds the row create_from_transaction would collide with" do+ setup_covering_family+ [+ create_transaction(account: @account, amount: 100, merchant: @merchant),+ create_transaction(account: @account, amount: 40, name: "CITY WATER 0042")+ ].each do |entry|+ transaction = entry.entryable+ assert_nil RecurringTransaction.identity_taken_by(transaction), "nothing holds the key yet"++ created = RecurringTransaction.create_from_transaction(transaction)+ created.update!(status: "ended")++ assert_nil @family.recurring_transactions.covering(entry), "precondition: covering skips the ended series"+ assert_equal created, RecurringTransaction.identity_taken_by(transaction)+ assert_raises(ActiveRecord::RecordNotUnique) do+ RecurringTransaction.transaction(requires_new: true) { RecurringTransaction.create_from_transaction(transaction) }+ end+ end+ end++ # dedup_scope carries the amount, so another price tier is a new key.+ test "identity_taken_by leaves another price tier free" do+ setup_covering_family+ RecurringTransaction.create_from_transaction(create_transaction(account: @account, amount: 100, merchant: @merchant).entryable)+ other_tier = create_transaction(account: @account, amount: 120, merchant: @merchant).entryable++ assert_nil RecurringTransaction.identity_taken_by(other_tier)+ end++ # The matcher never pays an ordinary bill with a transfer leg, so neither+ # does this check by name or merchant. A leg already allocated to a series+ # is still covered by it.+ test "covering does not match a transfer leg to a bill by identity" do+ setup_covering_family+ entry = create_transaction(account: @account, amount: 50, name: "Netflix")+ bill = covering_series(name: "Netflix", amount: 50)+ assert_equal bill, @family.recurring_transactions.covering(entry), "precondition: the ordinary charge is covered"++ entry.entryable.update!(kind: "funds_movement")++ assert_nil @family.recurring_transactions.covering(entry.reload)++ bill.recurring_occurrences.order(:due_on).first.allocations.create!(+ entry: entry, allocated_amount: 50, currency: "USD", source: "user_created"+ )++ assert_equal bill, @family.recurring_transactions.covering(entry)+ end++ # A recurring transfer is identified by its account pair, never by name, as+ # in the matcher, so a same-named charge is not its payment.+ test "covering ignores a recurring transfer" do+ setup_covering_family+ savings = @family.accounts.create! name: "Savings", balance: 0, currency: "USD", accountable: Depository.new+ entry = create_transaction(account: @account, amount: 100, name: "Savings top-up")+ @family.recurring_transactions.create!(+ account: @account, destination_account: savings, name: "Savings top-up", amount: 100, currency: "USD",+ expected_day_of_month: Date.current.day, last_occurrence_date: 1.month.ago.to_date,+ next_expected_date: Date.current, status: "active", manual: true, occurrence_count: 1+ )++ assert_nil @family.recurring_transactions.covering(entry)+ end+test "matching_transactions with amount variance matches within range" do# Create manual recurring with variance for day 15 of the monthrecurring = @family.recurring_transactions.create!(@@ -1584,4 +1823,19 @@ class RecurringTransactionTest < ActiveSupport::TestCasestatus: "active"}.merge(overrides))end++ def setup_covering_family+ @family = families(:empty)+ @account = @family.accounts.create! name: "Test", balance: 0, currency: "USD", accountable: Depository.new+ @merchant = @family.merchants.create! name: "Betashares"+ end++ def covering_series(amount:, merchant: nil, name: nil, account: @account, currency: "USD", status: "active", manual: true, dedup_scope: "")+ @family.recurring_transactions.create!(+ account: account, merchant: merchant, name: name, amount: amount, currency: currency,+ dedup_scope: dedup_scope, expected_day_of_month: Date.current.day,+ last_occurrence_date: 1.month.ago.to_date, next_expected_date: Date.current,+ status: status, manual: manual, occurrence_count: 1+ )+ endenddiff --git a/test/models/transaction_test.rb b/test/models/transaction_test.rbindex ddc3c1fb74..7a02237403 100644--- a/test/models/transaction_test.rb+++ b/test/models/transaction_test.rb@@ -3,92 +3,6 @@ require "test_helper"class TransactionTest < ActiveSupport::TestCaseinclude EntriesTestHelper- test "existing_manual_recurring_transaction finds a match by merchant" do- family = families(:empty)- account = family.accounts.create! name: "Test", balance: 0, currency: "USD", accountable: Depository.new- merchant = family.merchants.create! name: "Test Merchant"- entry = create_transaction(account: account, amount: 100, merchant: merchant)- transaction = entry.entryable-- recurring = family.recurring_transactions.create!(- account: account,- merchant: merchant,- amount: entry.amount,- currency: entry.currency,- expected_day_of_month: entry.date.day,- last_occurrence_date: entry.date,- next_expected_date: 1.month.from_now,- status: "active",- manual: true,- occurrence_count: 1- )-- assert_equal recurring, transaction.existing_manual_recurring_transaction- end-- test "existing_manual_recurring_transaction finds a match by name when no merchant" do- family = families(:empty)- account = family.accounts.create! name: "Test", balance: 0, currency: "USD", accountable: Depository.new- entry = create_transaction(account: account, amount: 50, name: "Netflix")- transaction = entry.entryable-- recurring = family.recurring_transactions.create!(- account: account,- name: "Netflix",- amount: entry.amount,- currency: entry.currency,- expected_day_of_month: entry.date.day,- last_occurrence_date: entry.date,- next_expected_date: 1.month.from_now,- status: "active",- manual: true,- occurrence_count: 1- )-- assert_equal recurring, transaction.existing_manual_recurring_transaction- end-- test "existing_manual_recurring_transaction returns nil when no manual recurring transaction matches" do- family = families(:empty)- account = family.accounts.create! name: "Test", balance: 0, currency: "USD", accountable: Depository.new- other_account = family.accounts.create! name: "Other", balance: 0, currency: "USD", accountable: Depository.new- merchant = family.merchants.create! name: "Test Merchant"- other_merchant = family.merchants.create! name: "Other Merchant"- entry = create_transaction(account: account, amount: 100, merchant: merchant)- transaction = entry.entryable-- base_attrs = {- expected_day_of_month: entry.date.day,- last_occurrence_date: entry.date,- next_expected_date: 1.month.from_now,- status: "active",- occurrence_count: 1- }-- # Differs by account- family.recurring_transactions.create!(base_attrs.merge(- account: other_account, merchant: merchant, amount: entry.amount, currency: entry.currency, manual: true- ))- # Differs by merchant- family.recurring_transactions.create!(base_attrs.merge(- account: account, merchant: other_merchant, amount: entry.amount, currency: entry.currency, manual: true- ))- # Differs by amount- family.recurring_transactions.create!(base_attrs.merge(- account: account, merchant: merchant, amount: entry.amount + 1, currency: entry.currency, manual: true- ))- # Differs by currency- family.recurring_transactions.create!(base_attrs.merge(- account: account, merchant: merchant, amount: entry.amount, currency: "EUR", manual: true- ))- # Differs by manual flag- family.recurring_transactions.create!(base_attrs.merge(- account: account, merchant: merchant, amount: entry.amount, currency: entry.currency, manual: false- ))-- assert_nil transaction.existing_manual_recurring_transaction- end-test "pending? is true when extra.simplefin.pending is truthy" dotransaction = Transaction.new(extra: { "simplefin" => { "pending" => true } })