The personal finance app for everyone (by everyone)
Ruby
Apply a bill's category to the transactions it is matched with (#5324)
Chris Werner Raua56be0696d22
diff --git a/app/controllers/recurring_allocations_controller.rb b/app/controllers/recurring_allocations_controller.rbindex 8c2cc800c4..93e08a1641 100644--- a/app/controllers/recurring_allocations_controller.rb+++ b/app/controllers/recurring_allocations_controller.rb@@ -13,7 +13,8 @@ class RecurringAllocationsController < ApplicationControlleramount: params[:amount].presence,# Defaults to today via RecurringAllocation's callback; accepting a date# lets someone record last Tuesday's payment as last Tuesday.- paid_on: parse_paid_on(params[:paid_on])+ paid_on: parse_paid_on(params[:paid_on]),+ categorize: annotatable?(entry))redirect_with notice: t(".success")@@ -40,7 +41,7 @@ class RecurringAllocationsController < ApplicationControlleroccurrence = allocation.recurring_occurrenceensure_series_writable(occurrence)- RecurringTransaction::Allocator.new(occurrence).confirm_suggestion!(allocation)+ RecurringTransaction::Allocator.new(occurrence).confirm_suggestion!(allocation, categorize: annotatable?(allocation.entry))redirect_with_return notice: t(".success")end@@ -76,6 +77,12 @@ class RecurringAllocationsController < ApplicationControllerraise ActiveRecord::RecordNotFoundend+ # Linking only needs read access to the transaction; setting its category+ # needs the right to annotate it.+ def annotatable?(entry)+ entry.nil? || Current.annotatable_entries.exists?(id: entry.id)+ end+def find_allocationRecurringAllocation.joins(recurring_occurrence: :recurring_transaction)diff --git a/app/models/data_enrichment.rb b/app/models/data_enrichment.rbindex b99e7711e3..706d642564 100644--- a/app/models/data_enrichment.rb+++ b/app/models/data_enrichment.rb@@ -17,6 +17,7 @@ class DataEnrichment < ApplicationRecordmonobank: "monobank",plaid: "plaid",questrade: "questrade",+ recurring_bill: "recurring_bill",redbark: "redbark",rule: "rule",sharesight: "sharesight",diff --git a/app/models/recurring_transaction/allocator.rb b/app/models/recurring_transaction/allocator.rbindex e396b1383d..ff51bf3ac5 100644--- a/app/models/recurring_transaction/allocator.rb+++ b/app/models/recurring_transaction/allocator.rb@@ -106,7 +106,10 @@ class RecurringTransaction# entry-less manual payment. Amounts are in the occurrence's currency;# a cross-currency entry converts at its own date's rate, or requires an# explicit amount when no rate exists.- def allocate!(amount: nil, entry: nil, paid_on: nil, source: nil, cap_at_remaining: false)+ #+ # categorize: true applies the bill's category to the entry. It is opt-in+ # because only the caller knows whether its user may annotate the transaction.+ def allocate!(amount: nil, entry: nil, paid_on: nil, source: nil, cap_at_remaining: false, categorize: false)occurrence.with_lock dowith_entry_lock(entry) doallocated, source_amount, source_currency = resolve_amounts(amount, entry)@@ -138,6 +141,7 @@ class RecurringTransactionlearn_from_manual_attach!(allocation) if entryallocation = promote_settlement!(allocation) if entry && amount.blank?+ apply_bill_category!(entry) if categorizerefresh_close_state!allocationend@@ -187,23 +191,49 @@ class RecurringTransactionpaid_on: entry.date)- refresh_close_state! if state == "confirmed"+ if state == "confirmed"+ apply_bill_category!(entry) if matcher_may_categorize?(entry)+ refresh_close_state!+ endallocationendendend# Accepting a suggestion makes it a real payment.- def confirm_suggestion!(allocation)+ #+ # categorize: true for a caller whose user may annotate the transaction; a+ # read-only account share links a payment without editing it.+ def confirm_suggestion!(allocation, categorize: false)occurrence.with_lock dowith_entry_lock(allocation.entry) dofreeze_expected_amount!+ # Only the move from suggested to confirmed makes a payment: a replayed+ # confirmation of a confirmed one must not categorize it later.+ first_confirmation = allocation.reload.allocation_suggested?allocation.update!(state: "confirmed", source: "user_confirmed")+ apply_bill_category!(allocation.entry) if categorize && first_confirmationrefresh_close_state!endendend+ # The Matcher re-attached a confirmed payment to the transaction that+ # replaced its original (a provider reposting it): the replacement is the+ # payment now, so it takes the bill's category the original would have.+ def categorize_reattached!(allocation)+ occurrence.with_lock do+ # The caller's copy may predate a confirmation, so the state is read+ # again under the lock.+ allocation.reload+ next unless allocation.allocation_confirmed? && allocation.entry++ with_entry_lock(allocation.entry) do+ apply_bill_category!(allocation.entry) if matcher_may_categorize?(allocation.entry)+ end+ end+ end+# Records the (series, entry) pair so the matcher never proposes it again.def reject_suggestion!(allocation)occurrence.with_lock do@@ -277,6 +307,45 @@ class RecurringTransactionoccurrence.update!(expected_amount: occurrence.resolved_expected_amount)end+ # A bill's category says what its payments are, so a payment confirmed+ # against it picks that category up. Only a blank, unlocked category is+ # filled: anything the user, a rule or a provider already decided stays,+ # and releasing the payment later leaves the category in place. Not+ # locked afterwards, so the user can still change it and a rule can still+ # override it.+ #+ # The transaction row is locked and re-read first: the Matcher loaded it+ # before getting here, so a category the user committed since would still+ # look blank on the loaded copy and be overwritten.+ def apply_bill_category!(entry)+ category_id = occurrence.recurring_transaction.category_id+ return if category_id.blank? || entry.nil?++ transaction = entry.entryable+ return unless transaction.is_a?(Transaction)++ transaction.with_lock do+ next unless transaction.category_id.blank? && transaction.category_editable?+ next unless Category.exists?(id: category_id)++ transaction.enrich_attribute(:category_id, category_id, source: "recurring_bill")+ end+ rescue ActiveRecord::InvalidForeignKey+ # The category was deleted between the check and the write. The payment+ # is still a payment; it just stays uncategorized.+ nil+ end++ # Matching runs with no signed-in user, so the user-facing access check+ # cannot be made. A bill tied to an account only ever matches that+ # account's transactions, and whoever may edit the bill may annotate them.+ # A bill that is not tied to an account matches the whole family, so the+ # matcher categorizes nothing for it; it is categorized when a person+ # confirms the payment, with that person's own access.+ def matcher_may_categorize?(_entry)+ occurrence.recurring_transaction.account_id.present?+ end+def close_worthy?expected = occurrence.resolved_expected_amountreturn false unless expected.positive?diff --git a/app/models/recurring_transaction/matcher.rb b/app/models/recurring_transaction/matcher.rbindex 7da30b078f..3606d47654 100644--- a/app/models/recurring_transaction/matcher.rb+++ b/app/models/recurring_transaction/matcher.rb@@ -128,7 +128,10 @@ class RecurringTransaction.includes(:entryable).find { |entry| repair_identity?(series, entry) }- allocation.update!(entry: replacement) if replacement+ next unless replacement++ allocation.update!(entry: replacement)+ Allocator.new(allocation.recurring_occurrence).categorize_reattached!(allocation)endenddiff --git a/test/controllers/recurring_allocations_controller_test.rb b/test/controllers/recurring_allocations_controller_test.rbindex b5c60074f7..6eeec81abc 100644--- a/test/controllers/recurring_allocations_controller_test.rb+++ b/test/controllers/recurring_allocations_controller_test.rb@@ -124,4 +124,72 @@ class RecurringAllocationsControllerTest < ActionDispatch::IntegrationTestassert_equal translation, I18n.t(key, locale: :de, fallback: false)endend++ test "confirming a suggestion on an account-less bill categorizes the transaction only for someone who may annotate it" do+ category = @family.categories.create!(name: "Card fees", color: "#e99537", lucide_icon: "shapes")+ bill = @family.recurring_transactions.create!(+ name: "Card Annual Fee", amount: 95, currency: "USD", category: category,+ expected_day_of_month: Date.current.day, anchor_date: Date.current,+ last_occurrence_date: Date.current, next_expected_date: Date.current,+ status: "active", manual: true+ )+ occurrence = bill.recurring_occurrences.order(:due_on).first+ suggest = lambda do+ entry = accounts(:credit_card).entries.create!(+ date: Date.current, amount: 95, currency: "USD", name: "ANNUAL FEE", entryable: Transaction.new+ )+ suggestion = RecurringTransaction::Allocator.new(occurrence).allocate_matched!(+ entry: entry, state: "suggested", confidence: 0.7, signals: { name: 0.35 }+ )+ [ entry, suggestion ]+ end++ # family_member has the card read-only: the confirmation works, the edit does not.+ member = users(:family_member)+ member.update!(preferences: (member.preferences || {}).merge("preview_features_enabled" => true))+ sign_in member+ entry, suggestion = suggest.call+ post confirm_recurring_allocation_url(suggestion)++ assert suggestion.reload.allocation_confirmed?+ assert_nil entry.transaction.reload.category++ sign_in @user+ entry, suggestion = suggest.call+ post confirm_recurring_allocation_url(suggestion)++ assert suggestion.reload.allocation_confirmed?+ assert_equal category, entry.transaction.reload.category+ end++ test "linking a payment categorizes the transaction only for someone who may annotate it" do+ category = @family.categories.create!(name: "Card fees", color: "#e99537", lucide_icon: "shapes")+ bill = @family.recurring_transactions.create!(+ name: "Card Annual Fee", amount: 95, currency: "USD", category: category,+ expected_day_of_month: Date.current.day, anchor_date: Date.current,+ last_occurrence_date: Date.current, next_expected_date: Date.current,+ status: "active", manual: true+ )+ occurrence = bill.recurring_occurrences.order(:due_on).first+ entry = accounts(:credit_card).entries.create!(+ date: Date.current, amount: 95, currency: "USD", name: "ANNUAL FEE", entryable: Transaction.new+ )++ # family_member has the card read-only: the link works, the edit does not.+ member = users(:family_member)+ member.update!(preferences: (member.preferences || {}).merge("preview_features_enabled" => true))+ sign_in member+ post recurring_occurrence_allocations_url(occurrence), params: { entry_id: entry.id }++ assert_equal 1, occurrence.reload.allocations.count+ assert_nil entry.transaction.reload.category++ # The owner of the account may annotate it.+ entry.recurring_allocations.destroy_all if entry.respond_to?(:recurring_allocations)+ RecurringAllocation.where(entry: entry).destroy_all+ sign_in @user+ post recurring_occurrence_allocations_url(occurrence), params: { entry_id: entry.id }++ assert_equal category, entry.transaction.reload.category+ endenddiff --git a/test/models/recurring_transaction/allocator_test.rb b/test/models/recurring_transaction/allocator_test.rbindex 5371764756..3e78444c81 100644--- a/test/models/recurring_transaction/allocator_test.rb+++ b/test/models/recurring_transaction/allocator_test.rb@@ -689,6 +689,215 @@ class RecurringTransaction::AllocatorTest < ActiveSupport::TestCaseassert_equal 2080, series.recurring_price_changes.order(:effective_on).last.new_amountend+ # A bill's category is the user's statement of what its payments are, so a+ # confirmed payment inherits it instead of being categorized a second time.+ # Only a blank, unlocked category is filled: a locked one is a user, rule or+ # provider decision, and the bill must not undo it.+ test "a confirmed manual attach gives an uncategorized transaction the bill's category" do+ category = bill_category!+ entry = entry_for(2000)++ @allocator.allocate!(entry: entry, categorize: true)++ transaction = entry.transaction.reload+ assert_equal category, transaction.category+ assert_not transaction.locked?(:category_id), "a bill-set category stays overridable by the user"+ assert_equal "recurring_bill", transaction.data_enrichments.find_by(attribute_name: "category_id").source+ end++ # The caller knows whether its user may annotate the transaction, so+ # categorizing is something it asks for, never something it gets by default.+ test "allocate! does not categorize unless asked to" do+ bill_category!+ entry = entry_for(2000)++ @allocator.allocate!(entry: entry)++ assert_nil entry.transaction.reload.category+ end++ test "confirm_suggestion! does not categorize unless asked to" do+ bill_category!+ entry = entry_for(2000)+ allocation = @allocator.allocate_matched!(entry: entry, state: "suggested", confidence: 0.8, signals: {})++ @allocator.confirm_suggestion!(allocation)++ assert_nil entry.transaction.reload.category+ end++ test "a confirmed auto match gives an uncategorized transaction the bill's category" do+ category = bill_category!+ entry = entry_for(2000)++ @allocator.allocate_matched!(entry: entry, state: "confirmed", confidence: 1, signals: {})++ assert_equal category, entry.transaction.reload.category+ end++ test "a suggested match leaves the category alone until the suggestion is confirmed" do+ category = bill_category!+ entry = entry_for(2000)++ allocation = @allocator.allocate_matched!(entry: entry, state: "suggested", confidence: 0.8, signals: {})+ assert_nil entry.transaction.reload.category++ @allocator.confirm_suggestion!(allocation, categorize: true)+ assert_equal category, entry.transaction.reload.category+ end++ test "a transaction that already has a category keeps it" do+ bill_category!+ other = @family.categories.create!(name: "Other pick", color: "#e99537", lucide_icon: "shapes")+ entry = entry_for(2000)+ entry.transaction.update!(category: other)++ @allocator.allocate!(entry: entry, categorize: true)++ assert_equal other, entry.transaction.reload.category+ end++ test "an uncategorized transaction whose category the user locked stays uncategorized" do+ bill_category!+ entry = entry_for(2000)+ entry.transaction.lock_attr!(:category_id)++ @allocator.allocate!(entry: entry, categorize: true)++ assert_nil entry.transaction.reload.category+ end++ test "a bill without a category changes nothing" do+ entry = entry_for(2000)++ @allocator.allocate!(entry: entry, categorize: true)++ assert_nil entry.transaction.reload.category+ assert_empty entry.transaction.data_enrichments+ end++ test "releasing the payment leaves the category the transaction picked up" do+ category = bill_category!+ entry = entry_for(2000)+ allocation = @allocator.allocate!(entry: entry, categorize: true)++ @allocator.unallocate!(allocation)++ assert_equal category, entry.transaction.reload.category,+ "the user may have relied on it; un-matching is not a request to uncategorize"+ end++ test "a payment without a transaction has nothing to categorize" do+ bill_category!++ assert_nothing_raised { @allocator.allocate!(amount: 500, categorize: true) }+ end++ # Auto-matching has no signed-in user, and a bill that is not tied to an+ # account matches anything in the family, so only a person's own confirmation+ # (with their own access) categorizes for it.+ test "an account-less bill does not categorize an auto match" do+ bill_category!+ @rent.update!(account: nil)+ entry = card_entry_for(2000)++ @allocator.allocate_matched!(entry: entry, state: "confirmed", confidence: 1, signals: {})++ assert_nil entry.transaction.reload.category+ end++ test "an account-less bill categorizes when a person confirms the suggestion" do+ category = bill_category!+ @rent.update!(account: nil)+ entry = card_entry_for(2000)+ suggestion = @allocator.allocate_matched!(entry: entry, state: "suggested", confidence: 0.7, signals: {})+ assert_nil entry.transaction.reload.category++ @allocator.confirm_suggestion!(suggestion, categorize: true)++ assert_equal category, entry.transaction.reload.category+ end++ test "an account-less bill does not categorize a repaired orphan on its own" do+ bill_category!+ @rent.update!(account: nil)+ entry = card_entry_for(2000)+ allocation = @allocator.allocate!(entry: entry)++ @allocator.categorize_reattached!(allocation)++ assert_nil entry.transaction.reload.category+ end++ test "a category committed after the matcher loaded the transaction is not overwritten" do+ bill_category!+ other = @family.categories.create!(name: "Picked meanwhile", color: "#e99537", lucide_icon: "shapes")+ entry = entry_for(2000)+ stale = Entry.includes(:entryable).find(entry.id)+ stale.entryable # loaded while still blank++ Transaction.where(id: entry.entryable_id).update_all(category_id: other.id)+ @allocator.allocate_matched!(entry: stale, state: "confirmed", confidence: 1, signals: {})++ assert_equal other, entry.transaction.reload.category+ end++ test "confirming an allocation that is already confirmed does not categorize it later" do+ entry = entry_for(2000)+ allocation = @allocator.allocate_matched!(entry: entry, state: "suggested", confidence: 0.8, signals: {})+ @allocator.confirm_suggestion!(allocation, categorize: true)+ assert_nil entry.transaction.reload.category++ bill_category!+ @allocator.confirm_suggestion!(allocation.reload, categorize: true)++ assert_nil entry.transaction.reload.category+ end++ test "a transaction whose category is not editable is not categorized" do+ bill_category!+ entry = entry_for(2000)+ Transaction.any_instance.stubs(:category_editable?).returns(false)++ @allocator.allocate!(entry: entry, categorize: true)++ assert_nil entry.transaction.reload.category+ end++ test "a category that cannot be written does not stop the payment from being confirmed" do+ bill_category!+ entry = entry_for(2000)+ Transaction.any_instance.stubs(:enrich_attribute).raises(ActiveRecord::InvalidForeignKey)++ allocation = @allocator.allocate!(entry: entry, categorize: true)++ assert allocation.persisted?+ assert allocation.allocation_confirmed?+ end++ test "re-attaching a payment confirmed since it was loaded still categorizes the replacement" do+ category = bill_category!+ entry = entry_for(2000)+ allocation = @allocator.allocate_matched!(entry: entry, state: "suggested", confidence: 0.8, signals: {})+ stale = RecurringAllocation.find(allocation.id)+ assert stale.allocation_suggested?++ allocation.update!(state: "confirmed", source: "user_confirmed")+ @allocator.categorize_reattached!(stale)++ assert_equal category, entry.transaction.reload.category+ end++ test "re-attaching a payment that is still only a suggestion does not categorize" do+ bill_category!+ entry = entry_for(2000)+ allocation = @allocator.allocate_matched!(entry: entry, state: "suggested", confidence: 0.8, signals: {})++ @allocator.categorize_reattached!(allocation)++ assert_nil entry.transaction.reload.category+ end+privatedef foreign_entry(amount:, currency:)@@ -713,6 +922,18 @@ class RecurringTransaction::AllocatorTest < ActiveSupport::TestCasecurrency: "USD", expected_amount: expected, status: "scheduled")end+ def bill_category!+ category = @family.categories.create!(name: "Housing bills", color: "#e99537", lucide_icon: "house")+ @rent.update!(category: category)+ category+ end++ def card_entry_for(amount)+ accounts(:credit_card).entries.create!(+ date: Date.current, amount: amount, currency: "USD", name: "Watson Property", entryable: Transaction.new+ )+ end+def entry_for(amount)@account.entries.create!(date: Date.current,diff --git a/test/models/recurring_transaction/matcher_test.rb b/test/models/recurring_transaction/matcher_test.rbindex 5c485ccd4a..f84c874e0c 100644--- a/test/models/recurring_transaction/matcher_test.rb+++ b/test/models/recurring_transaction/matcher_test.rb@@ -313,6 +313,22 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCaseassert_equal replacement.id, allocation.reload.entry_idend+ test "repair gives the replacement transaction the bill's category" do+ category = @family.categories.create!(name: "Utilities", color: "#e99537", lucide_icon: "zap")+ series = create_series(name: "POWER CO", amount: 60, day_offset: 2)+ series.update!(category: category)+ occurrence = series.recurring_occurrences.order(:due_on).first+ original = create_entry(amount: 60, date: Date.current, name: "POWER CO")+ @matcher.run!+ allocation = occurrence.allocations.sole+ original.destroy!++ replacement = create_entry(amount: 60, date: allocation.paid_on, name: "POWER CO POSTED")+ @matcher.repair_orphans!++ assert_equal category, replacement.transaction.reload.category+ end+test "repair re-attaches a recurring transfer's payment by its account pair, not its name" doseries = create_series(name: "Payment to Loan", amount: 500, day_offset: 0, destination: accounts(:loan))occurrence = first_occurrence(series)